use std::any::TypeId;
use std::borrow::Cow;
use std::collections::HashMap;
use std::fmt;
use std::sync::Arc;
use navree_kernel::BoxFuture;
use crate::collection::Collection;
use crate::column::{Assignment, Column, Filter};
use crate::error::Result;
use crate::exec::{Access, Executor, Target};
use crate::ir::{
AggregateFunction, ColumnRef, Expr, Operator, Order, QueryIr, SelectItem, TableRef, Where,
};
use crate::model::Model;
use crate::query::Builder;
use crate::record::Record;
use crate::relations::belongs_to::DefaultModel;
use crate::relations::core::{
Bound, Finisher, RelationCore, column_value, column_values, constrain, distribute, matching,
new_with, qualified, relation_builder_traits, relation_query_methods,
relation_retrieval_methods, restore_record, save_atomically,
};
use crate::relations::define::KeyColumn;
use crate::relations::eager::{EagerNode, EagerTree, RelationParts, constrained, prepare_query};
use crate::relations::existence::{ExistsRequest, build_subquery, columns_equal};
use crate::relations::keys::{RelationKey, distinct_keys, in_keys_on, key_of};
use crate::relations::morph::stored_type_of;
use crate::relations::one_of_many::OneOfMany;
use crate::relations::registry::{ErasedRelation, RelationKind, RelationMeta};
use crate::relations::{RelatedTo, Relation, private};
use crate::value::{Numeric, Value, is_null};
pub(crate) const ROW_COLUMN: &str = "navree_row";
pub(crate) fn limit_per_parent<R: Model>(query: Builder<R>, partition: Expr) -> Builder<R> {
if query.ir.limit.is_none() && query.ir.offset.is_none() {
return query;
}
let mut query = query.with_pending_default_counts();
let tree = query.take_eager();
let limit = query.ir.limit.take();
let offset = query.ir.offset.take().unwrap_or(0);
let mut inner = query.into_ir();
let orders = std::mem::take(&mut inner.orders);
inner.columns.push(SelectItem {
expr: Expr::RowNumber {
partition: vec![partition],
order: orders,
},
alias: Some(Cow::Borrowed(ROW_COLUMN)),
});
let mut outer = Builder::<R>::new();
outer.scopes_applied = true;
outer.ir.table = TableRef::subquery(inner, "navree_table");
outer.ir.columns = vec![SelectItem {
expr: Expr::All { table: None },
alias: None,
}];
let row = Expr::Column(ColumnRef::new(None::<&str>, ROW_COLUMN));
if offset > 0 {
outer = outer.where_(Filter::from(Where::Compare {
left: row.clone(),
op: Operator::Gt,
right: Expr::Value(Value::I64(i64::try_from(offset).unwrap_or(i64::MAX))),
}));
}
if let Some(limit) = limit {
let last = offset.saturating_add(limit);
outer = outer.where_(Filter::from(Where::Compare {
left: row.clone(),
op: Operator::Lte,
right: Expr::Value(Value::I64(i64::try_from(last).unwrap_or(i64::MAX))),
}));
}
outer.ir.orders = vec![Order::asc(row)];
outer.eager.tree = tree;
outer
}
pub(crate) fn drop_row_numbers<R: Model>(records: &mut [Record<R>]) {
for record in records {
record.extras.retain(|(column, _)| column != ROW_COLUMN);
}
}
struct HasKeys<'a> {
name: &'a str,
foreign_key: &'a str,
local_key: &'a str,
morph: Option<&'a str>,
}
impl HasKeys<'_> {
fn morph_condition<P: Model>(&self, table: &str) -> Option<Where> {
self.morph.map(|column| Where::Compare {
left: Expr::Column(qualified(table, column)),
op: Operator::Eq,
right: Expr::Value(Value::from(P::morph_name().into_owned())),
})
}
fn bound_conditions<P: Model, R: Model>(&self, parent: &P) -> Result<Option<Vec<Where>>> {
let value = column_value(parent, self.local_key, self.name)?;
if is_null(&value) {
return Ok(None);
}
let table = R::meta().table();
let foreign = qualified(table, self.foreign_key);
let mut conditions = vec![
Where::Compare {
left: Expr::Column(foreign.clone()),
op: Operator::Eq,
right: Expr::Value(value),
},
Where::Null {
expr: Expr::Column(foreign),
not: true,
},
];
conditions.extend(self.morph_condition::<P>(table));
Ok(Some(conditions))
}
fn eager_conditions<P: Model, R: Model>(
&self,
target: &Target<'_>,
keys: &[(RelationKey, Value)],
) -> Vec<Where> {
let table = R::meta().table();
let mut conditions = vec![in_keys_on(target, qualified(table, self.foreign_key), keys)];
conditions.extend(self.morph_condition::<P>(table));
conditions
}
fn exists<P: Model, R: Model>(
&self,
definition: &Builder<R>,
request: ExistsRequest,
one_of_many: Option<&OneOfMany<R>>,
) -> Result<QueryIr> {
let parent_table = P::meta().table();
let table = R::meta().table();
let aliased = (table == parent_table).then_some(table);
let local = qualified(parent_table, self.local_key);
let foreign_key = self.foreign_key.to_owned();
let morph = self.morph_condition::<P>(table);
let group_by = self.group_by::<R>();
build_subquery::<R>(
P::meta(),
definition,
request,
self.name,
aliased,
|query, _| {
let query = match one_of_many {
Some(one) => one.apply(query, self.name, &group_by, Vec::new(), &|query| query),
None => query,
};
match morph {
Some(morph) => query.where_(Filter::from(morph)),
None => query,
}
},
|alias| {
vec![columns_equal(
local,
qualified(alias.unwrap_or(table), &foreign_key),
)]
},
)
}
fn group_by<R: Model>(&self) -> Vec<ColumnRef> {
let table = R::meta().table();
let mut columns = vec![qualified(table, self.foreign_key)];
if let Some(morph) = self.morph {
columns.push(qualified(table, morph));
}
columns
}
fn fill<P: Model, R: Model>(&self, parent: &P, record: &mut Record<R>) -> Result<()> {
let value = column_value(parent, self.local_key, self.name)?;
record.model.set_value(self.foreign_key, value)?;
if let Some(morph) = self.morph {
record.model.set_value(morph, stored_type_of::<P>()?)?;
}
Ok(())
}
async fn load<P: Model, R: Model>(
&self,
target: &Target<'_>,
parents: &[Record<P>],
query: Builder<R>,
node: &EagerNode,
one_of_many: Option<&OneOfMany<R>>,
) -> Result<(
Vec<Option<RelationKey>>,
HashMap<RelationKey, Vec<Record<R>>>,
)> {
let values = column_values(parents, self.local_key, self.name)?;
let parent_keys: Vec<Option<RelationKey>> = values.iter().map(key_of).collect();
let keys = distinct_keys(values);
let mut groups: HashMap<RelationKey, Vec<Record<R>>> = HashMap::new();
if keys.is_empty() {
return Ok((parent_keys, groups));
}
let table = R::meta().table();
let query = prepare_query(query, node, table, &[self.foreign_key])?;
let conditions = self.eager_conditions::<P, R>(target, &keys);
let query = match one_of_many {
Some(one) => one.apply(
query,
self.name,
&self.group_by::<R>(),
conditions,
&|query| query,
),
None => constrain(query, conditions),
};
let query = limit_per_parent(query, Expr::Column(qualified(table, self.foreign_key)));
let mut records = query.fetch(target).await?.into_vec();
drop_row_numbers(&mut records);
if node.autoload {
crate::relations::lazy::group_records(records.iter_mut());
}
for record in records {
let value = column_value(&record.model, self.foreign_key, self.name)?;
if let Some(key) = key_of(&value) {
groups.entry(key).or_default().push(record);
}
}
Ok((parent_keys, groups))
}
}
fn set_inverse<P: Model, R: Model>(inverse: &str, parent: &Record<P>, children: &mut [Record<R>]) {
let snapshot = parent.without_relations();
for child in children {
child
.relations
.set_relation(inverse.to_owned(), Some(snapshot.clone()));
}
}
fn inverse_finisher<P: Model, R: Model>(
inverse: &Option<Cow<'static, str>>,
parent: &P,
) -> Option<Finisher<R>> {
let inverse = inverse.clone()?;
let snapshot = Record::stored(parent.clone());
Some(Box::new(move |records: &mut [Record<R>]| {
set_inverse(&inverse, &snapshot, records);
Ok(())
}))
}
macro_rules! has_write_methods {
() => {
fn keys(&self) -> HasKeys<'_> {
HasKeys {
name: &self.core.name,
foreign_key: &self.foreign_key,
local_key: &self.local_key,
morph: self.morph.as_deref(),
}
}
fn fill_foreign(&self, record: &mut Record<R>) -> Result<()> {
let parent = self.core.parent()?;
self.keys().fill::<P, R>(parent, record)?;
if let Some(inverse) = &self.inverse {
record
.relations
.set_relation(inverse.to_string(), Some(Record::stored(parent.clone())));
}
Ok(())
}
pub fn make(&self, model: R) -> Result<Record<R>> {
let mut record = Record::new(model);
self.fill_foreign(&mut record)?;
Ok(record)
}
pub fn make_many(&self, models: impl IntoIterator<Item = R>) -> Result<Collection<R>> {
models.into_iter().map(|model| self.make(model)).collect()
}
pub async fn save<E: Executor + ?Sized>(
&self,
exec: &E,
record: &mut Record<R>,
) -> Result<bool> {
self.fill_foreign(record)?;
record.save(exec).await
}
pub async fn save_quietly<E: Executor + ?Sized>(
&self,
exec: &E,
record: &mut Record<R>,
) -> Result<bool> {
crate::events::without_events(self.save(exec, record)).await
}
pub async fn save_many<E: Executor + ?Sized>(
&self,
exec: &E,
records: &mut [Record<R>],
) -> Result<bool> {
let mut all = true;
for record in records {
all &= self.save(exec, record).await?;
}
Ok(all)
}
pub async fn save_many_quietly<E: Executor + ?Sized>(
&self,
exec: &E,
records: &mut [Record<R>],
) -> Result<bool> {
crate::events::without_events(self.save_many(exec, records)).await
}
pub async fn create<E: Executor + ?Sized>(&self, exec: &E, model: R) -> Result<Record<R>> {
let mut record = self.make(model)?;
record.save(exec).await?;
Ok(record)
}
pub async fn create_quietly<E: Executor + ?Sized>(
&self,
exec: &E,
model: R,
) -> Result<Record<R>> {
crate::events::without_events(self.create(exec, model)).await
}
pub async fn create_many<E: Executor + ?Sized>(
&self,
exec: &E,
models: impl IntoIterator<Item = R>,
) -> Result<Collection<R>> {
let mut records = Collection::new();
for model in models {
records.push(self.create(exec, model).await?);
}
Ok(records)
}
pub async fn create_many_quietly<E: Executor + ?Sized>(
&self,
exec: &E,
models: impl IntoIterator<Item = R>,
) -> Result<Collection<R>> {
crate::events::without_events(self.create_many(exec, models)).await
}
pub async fn force_create<E: Executor + ?Sized>(
&self,
exec: &E,
attributes: impl IntoIterator<Item = Assignment>,
) -> Result<Record<R>>
where
R: Default,
{
let attributes: Vec<Assignment> = attributes.into_iter().collect();
let mut record = new_with::<R>(&attributes, |_| {})?;
self.fill_foreign(&mut record)?;
record.save(exec).await?;
Ok(record)
}
pub async fn force_create_quietly<E: Executor + ?Sized>(
&self,
exec: &E,
attributes: impl IntoIterator<Item = Assignment>,
) -> Result<Record<R>>
where
R: Default,
{
let attributes: Vec<Assignment> = attributes.into_iter().collect();
crate::events::without_events(self.force_create(exec, attributes)).await
}
pub async fn force_create_many<E, A>(
&self,
exec: &E,
rows: impl IntoIterator<Item = A>,
) -> Result<Collection<R>>
where
E: Executor + ?Sized,
A: IntoIterator<Item = Assignment>,
R: Default,
{
let mut records = Collection::new();
for attributes in rows {
records.push(self.force_create(exec, attributes).await?);
}
Ok(records)
}
pub async fn force_create_many_quietly<E, A>(
&self,
exec: &E,
rows: impl IntoIterator<Item = A>,
) -> Result<Collection<R>>
where
E: Executor + ?Sized,
A: IntoIterator<Item = Assignment>,
R: Default,
{
let rows: Vec<Vec<Assignment>> = rows
.into_iter()
.map(|row| row.into_iter().collect())
.collect();
crate::events::without_events(self.force_create_many(exec, rows)).await
}
pub async fn find_or_new<E: Executor + ?Sized>(
self,
exec: &E,
key: impl Into<R::Key>,
) -> Result<Record<R>>
where
R: Default,
{
let blank = self.make(R::default())?;
Ok(self.find(exec, key).await?.unwrap_or(blank))
}
pub async fn first_or_new<E: Executor + ?Sized>(
self,
exec: &E,
attributes: impl IntoIterator<Item = Assignment>,
fill: impl FnOnce(&mut R) + Send,
) -> Result<Record<R>>
where
R: Default,
{
let attributes: Vec<Assignment> = attributes.into_iter().collect();
let found = self
.clone()
.scope(|query| matching(query, &attributes))
.first(exec)
.await?;
match found {
Some(record) => Ok(record),
None => {
let mut record = new_with::<R>(&attributes, fill)?;
self.fill_foreign(&mut record)?;
Ok(record)
}
}
}
pub async fn first_or_create<E: Executor + ?Sized>(
self,
exec: &E,
attributes: impl IntoIterator<Item = Assignment>,
fill: impl FnOnce(&mut R) + Send,
) -> Result<Record<R>>
where
R: Default,
{
let attributes: Vec<Assignment> = attributes.into_iter().collect();
let target = exec.target(Access::Write).await?;
if let Some(found) = self.clone().first_matching(&target, &attributes).await? {
return Ok(found);
}
self.create_or_first_on(&target, &attributes, fill).await
}
pub async fn create_or_first<E: Executor + ?Sized>(
self,
exec: &E,
attributes: impl IntoIterator<Item = Assignment>,
fill: impl FnOnce(&mut R) + Send,
) -> Result<Record<R>>
where
R: Default,
{
let attributes: Vec<Assignment> = attributes.into_iter().collect();
let target = exec.target(Access::Write).await?;
self.create_or_first_on(&target, &attributes, fill).await
}
pub async fn update_or_create<E: Executor + ?Sized>(
self,
exec: &E,
attributes: impl IntoIterator<Item = Assignment>,
fill: impl Fn(&mut R) + Send + Sync,
) -> Result<Record<R>>
where
R: Default,
{
let attributes: Vec<Assignment> = attributes.into_iter().collect();
let target = exec.target(Access::Write).await?;
let mut record = match self.clone().first_matching(&target, &attributes).await? {
Some(found) => found,
None => self.create_or_first_on(&target, &attributes, &fill).await?,
};
if !record.was_recently_created() && record.exists() {
fill(&mut record.model);
crate::persist::save(&target, &mut record).await?;
}
Ok(record)
}
pub async fn increment_or_create<E, T>(
self,
exec: &E,
attributes: impl IntoIterator<Item = Assignment>,
column: Column<R, T>,
default: T,
step: T,
) -> Result<Record<R>>
where
E: Executor + ?Sized,
T: Numeric,
R: Default,
{
let attributes: Vec<Assignment> = attributes.into_iter().collect();
let mut with_default = attributes.clone();
with_default.push(column.set(default));
let target = exec.target(Access::Write).await?;
let mut record = match self.clone().first_matching(&target, &attributes).await? {
Some(found) => found,
None => {
self.create_or_first_on(&target, &with_default, |_| {})
.await?
}
};
if !record.was_recently_created() && record.exists() {
crate::persist::increment(
&target,
&mut record,
vec![(column, step)],
false,
Vec::new(),
)
.await?;
}
Ok(record)
}
pub async fn restore_or_create<E: Executor + ?Sized>(
self,
exec: &E,
attributes: impl IntoIterator<Item = Assignment>,
fill: impl FnOnce(&mut R) + Send,
) -> Result<Record<R>>
where
R: Default,
{
let attributes: Vec<Assignment> = attributes.into_iter().collect();
let target = exec.target(Access::Write).await?;
let relation = self.with_trashed();
let mut record = match relation
.clone()
.first_matching(&target, &attributes)
.await?
{
Some(found) => found,
None => {
relation
.create_or_first_on(&target, &attributes, fill)
.await?
}
};
restore_record(&target, &mut record).await?;
Ok(record)
}
pub async fn create_or_restore<E: Executor + ?Sized>(
self,
exec: &E,
attributes: impl IntoIterator<Item = Assignment>,
fill: impl FnOnce(&mut R) + Send,
) -> Result<Record<R>>
where
R: Default,
{
let attributes: Vec<Assignment> = attributes.into_iter().collect();
let target = exec.target(Access::Write).await?;
let mut record = self
.with_trashed()
.create_or_first_on(&target, &attributes, fill)
.await?;
restore_record(&target, &mut record).await?;
Ok(record)
}
async fn first_matching(
self,
target: &Target<'_>,
attributes: &[Assignment],
) -> Result<Option<Record<R>>> {
let bound = self
.scope(|query| matching(query, attributes))
.limit(1)
.bound()?;
if bound.empty {
return Ok(None);
}
let mut records = bound.query.clone().fetch(target).await?.into_vec();
bound.finish(&mut records)?;
Ok(records.into_iter().next())
}
async fn create_or_first_on(
self,
target: &Target<'_>,
attributes: &[Assignment],
fill: impl FnOnce(&mut R) + Send,
) -> Result<Record<R>>
where
R: Default,
{
let mut record = new_with::<R>(attributes, fill)?;
self.fill_foreign(&mut record)?;
match save_atomically(target, &mut record).await {
Ok(_) => Ok(record),
Err(error) if error.is_unique_violation() => {
match self.first_matching(target, attributes).await? {
Some(found) => Ok(found),
None => Err(error),
}
}
Err(error) => Err(error),
}
}
pub fn foreign_key_name(&self) -> &str {
&self.foreign_key
}
pub fn qualified_foreign_key_name(&self) -> String {
format!("{}.{}", R::meta().table(), self.foreign_key)
}
pub fn local_key_name(&self) -> &str {
&self.local_key
}
pub fn parent_key(&self) -> Option<Value> {
let parent = self.core.parent.as_ref()?;
column_value(parent, &self.local_key, &self.core.name).ok()
}
pub fn morph_type(&self) -> Option<&str> {
self.morph.as_deref()
}
pub fn morph_name(&self) -> Option<Cow<'static, str>> {
self.morph.as_ref().map(|_| P::morph_name())
}
pub fn local_key(mut self, column: impl KeyColumn<P>) -> Self {
self.local_key = column.key_column();
self
}
pub fn type_column(mut self, column: impl KeyColumn<R>) -> Self {
self.morph = Some(column.key_column());
self
}
pub fn id_column(mut self, column: impl KeyColumn<R>) -> Self {
self.foreign_key = column.key_column();
self
}
pub fn inverse(mut self, name: impl Into<Cow<'static, str>>) -> Self {
self.inverse = Some(name.into());
self
}
pub fn chaperone(self, name: impl Into<Cow<'static, str>>) -> Self {
self.inverse(name)
}
pub fn without_inverse(mut self) -> Self {
self.inverse = None;
self
}
pub fn without_chaperone(self) -> Self {
self.without_inverse()
}
pub async fn touch<E: Executor + ?Sized>(self, exec: &E) -> Result<u64> {
let target = exec.target(Access::Write).await?;
let bound = self.without_global_scopes().bound()?;
if bound.empty {
return Ok(0);
}
crate::relations::touch::touch_related(Some(bound.query), &target).await
}
};
}
pub struct HasOne<P: Model, R: Model> {
pub(crate) core: RelationCore<P, R>,
pub(crate) foreign_key: Cow<'static, str>,
pub(crate) local_key: Cow<'static, str>,
pub(crate) morph: Option<Cow<'static, str>>,
pub(crate) inverse: Option<Cow<'static, str>>,
pub(crate) default: Option<DefaultModel<P, R>>,
pub(crate) one_of_many: Option<OneOfMany<R>>,
}
pub type MorphOne<P, R> = HasOne<P, R>;
pub struct HasMany<P: Model, R: Model> {
pub(crate) core: RelationCore<P, R>,
pub(crate) foreign_key: Cow<'static, str>,
pub(crate) local_key: Cow<'static, str>,
pub(crate) morph: Option<Cow<'static, str>>,
pub(crate) inverse: Option<Cow<'static, str>>,
}
pub type MorphMany<P, R> = HasMany<P, R>;
impl<P: Model, R: Model> Clone for HasOne<P, R> {
fn clone(&self) -> Self {
HasOne {
core: self.core.clone(),
foreign_key: self.foreign_key.clone(),
local_key: self.local_key.clone(),
morph: self.morph.clone(),
inverse: self.inverse.clone(),
default: self.default.clone(),
one_of_many: self.one_of_many.clone(),
}
}
}
impl<P: Model, R: Model> Clone for HasMany<P, R> {
fn clone(&self) -> Self {
HasMany {
core: self.core.clone(),
foreign_key: self.foreign_key.clone(),
local_key: self.local_key.clone(),
morph: self.morph.clone(),
inverse: self.inverse.clone(),
}
}
}
impl<P: Model, R: Model> fmt::Debug for HasOne<P, R> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct(if self.morph.is_some() {
"MorphOne"
} else {
"HasOne"
})
.field("parent", &P::meta().name())
.field("related", &R::meta().name())
.field("name", &self.core.name)
.field("foreign_key", &self.foreign_key)
.field("local_key", &self.local_key)
.finish_non_exhaustive()
}
}
impl<P: Model, R: Model> fmt::Debug for HasMany<P, R> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct(if self.morph.is_some() {
"MorphMany"
} else {
"HasMany"
})
.field("parent", &P::meta().name())
.field("related", &R::meta().name())
.field("name", &self.core.name)
.field("foreign_key", &self.foreign_key)
.field("local_key", &self.local_key)
.finish_non_exhaustive()
}
}
relation_builder_traits!(HasOne);
relation_builder_traits!(HasMany);
impl<P: Model, R: Model> RelationParts<P, R> for HasOne<P, R> {
fn core_mut(&mut self) -> &mut RelationCore<P, R> {
&mut self.core
}
}
impl<P: Model, R: Model> RelationParts<P, R> for HasMany<P, R> {
fn core_mut(&mut self) -> &mut RelationCore<P, R> {
&mut self.core
}
}
fn morph_columns(name: &str) -> (Cow<'static, str>, Cow<'static, str>) {
(
Cow::Owned(format!("{name}_type")),
Cow::Owned(format!("{name}_id")),
)
}
impl<P: Model, R: Model> HasOne<P, R> {
pub(crate) fn new(parent: Option<P>, foreign_key: Cow<'static, str>) -> Self {
HasOne {
core: RelationCore::new(
parent,
Cow::Owned(crate::model::snake_case(R::meta().name())),
),
foreign_key,
local_key: Cow::Borrowed(P::meta().key_column()),
morph: None,
inverse: None,
default: None,
one_of_many: None,
}
}
pub(crate) fn new_morph(parent: Option<P>, name: &str) -> Self {
let (type_column, id_column) = morph_columns(name);
let mut relation = HasOne::new(parent, id_column);
relation.morph = Some(type_column);
relation
}
relation_query_methods!();
relation_retrieval_methods!();
has_write_methods!();
pub fn with_default(mut self) -> Self
where
R: Default,
{
self.default = Some(Arc::new(|_| R::default()));
self
}
pub fn with_default_value(mut self, model: R) -> Self {
self.default = Some(Arc::new(move |_| model.clone()));
self
}
pub fn with_default_fn(mut self, make: impl Fn(&P) -> R + Send + Sync + 'static) -> Self {
self.default = Some(Arc::new(make));
self
}
fn default_for(&self, parent: &P) -> Option<Record<R>> {
let make = self.default.as_ref()?;
let mut record = Record::new(make(parent));
let _ = self.keys().fill::<P, R>(parent, &mut record);
Some(record)
}
pub fn latest_of_many(self) -> Self {
self.of_many_columns(vec![(
Cow::Borrowed(R::meta().key_column()),
AggregateFunction::Max,
)])
}
pub fn oldest_of_many(self) -> Self {
self.of_many_columns(vec![(
Cow::Borrowed(R::meta().key_column()),
AggregateFunction::Min,
)])
}
pub fn latest_of_many_by(self, column: impl KeyColumn<R>) -> Self {
self.of_many_columns(vec![(column.key_column(), AggregateFunction::Max)])
}
pub fn oldest_of_many_by(self, column: impl KeyColumn<R>) -> Self {
self.of_many_columns(vec![(column.key_column(), AggregateFunction::Min)])
}
pub fn of_many<C: KeyColumn<R>>(
mut self,
columns: impl IntoIterator<Item = (C, AggregateFunction)>,
constraint: impl Fn(Builder<R>) -> Builder<R> + Send + Sync + 'static,
) -> Self {
let columns: Vec<(Cow<'static, str>, AggregateFunction)> = columns
.into_iter()
.map(|(column, function)| (column.key_column(), function))
.collect();
self = self.of_many_columns(columns);
if let Some(one) = &mut self.one_of_many {
one.constraint = Some(Arc::new(constraint));
}
self
}
fn of_many_columns(mut self, columns: Vec<(Cow<'static, str>, AggregateFunction)>) -> Self {
if let Some((column, function)) = columns.iter().find(|(_, function)| {
!matches!(function, AggregateFunction::Max | AggregateFunction::Min)
}) {
let message = format!(
"one of many picks by MAX or MIN, not {} of `{column}`",
function.sql_name()
);
self.core.query = self.core.query.with_error(message);
return self;
}
self.one_of_many = Some(OneOfMany::new(columns));
self
}
pub fn of_many_alias(mut self, alias: impl Into<Cow<'static, str>>) -> Self {
if let Some(one) = &mut self.one_of_many {
one.alias = Some(alias.into());
}
self
}
pub fn is_one_of_many(&self) -> bool {
self.one_of_many.is_some()
}
pub async fn is<E: Executor + ?Sized>(&self, exec: &E, record: &Record<R>) -> Result<bool> {
let Some(parent_key) = self.parent_key() else {
return Ok(false);
};
let foreign = column_value(&record.model, &self.foreign_key, &self.core.name)?;
if key_of(&parent_key).is_none() || key_of(&parent_key) != key_of(&foreign) {
return Ok(false);
}
if self.one_of_many.is_none() {
return Ok(true);
}
self.clone().where_key(record.key()).exists(exec).await
}
pub async fn is_not<E: Executor + ?Sized>(&self, exec: &E, record: &Record<R>) -> Result<bool> {
Ok(!self.is(exec, record).await?)
}
pub async fn results<E: Executor + ?Sized>(self, exec: &E) -> Result<Option<Record<R>>> {
let parent = self.core.parent()?.clone();
let default = self.default_for(&parent);
Ok(self.first(exec).await?.or(default))
}
pub(crate) fn bound(self) -> Result<Bound<R>> {
let parent = self.core.parent()?.clone();
let keys = self.keys();
let Some(conditions) = keys.bound_conditions::<P, R>(&parent)? else {
return Ok(Bound::nothing(self.core.query));
};
let group_by = keys.group_by::<R>();
let name = self.core.name.clone();
let finish = inverse_finisher(&self.inverse, &parent);
let query = match &self.one_of_many {
Some(one) => one.apply(self.core.query, &name, &group_by, conditions, &|query| {
query
}),
None => constrain(self.core.query, conditions),
};
Ok(Bound::new(query).finishing(finish))
}
}
impl<P: Model, R: Model> HasMany<P, R> {
pub(crate) fn new(parent: Option<P>, foreign_key: Cow<'static, str>) -> Self {
HasMany {
core: RelationCore::new(parent, Cow::Borrowed(R::meta().table())),
foreign_key,
local_key: Cow::Borrowed(P::meta().key_column()),
morph: None,
inverse: None,
}
}
pub(crate) fn new_morph(parent: Option<P>, name: &str) -> Self {
let (type_column, id_column) = morph_columns(name);
let mut relation = HasMany::new(parent, id_column);
relation.morph = Some(type_column);
relation
}
relation_query_methods!();
relation_retrieval_methods!();
has_write_methods!();
pub fn one(self) -> HasOne<P, R> {
HasOne {
core: self.core,
foreign_key: self.foreign_key,
local_key: self.local_key,
morph: self.morph,
inverse: self.inverse,
default: None,
one_of_many: None,
}
}
pub fn latest_of_many(self) -> HasOne<P, R> {
self.one().latest_of_many()
}
pub fn oldest_of_many(self) -> HasOne<P, R> {
self.one().oldest_of_many()
}
pub fn latest_of_many_by(self, column: impl KeyColumn<R>) -> HasOne<P, R> {
self.one().latest_of_many_by(column)
}
pub fn oldest_of_many_by(self, column: impl KeyColumn<R>) -> HasOne<P, R> {
self.one().oldest_of_many_by(column)
}
pub fn of_many<C: KeyColumn<R>>(
self,
columns: impl IntoIterator<Item = (C, AggregateFunction)>,
constraint: impl Fn(Builder<R>) -> Builder<R> + Send + Sync + 'static,
) -> HasOne<P, R> {
self.one().of_many(columns, constraint)
}
pub async fn results<E: Executor + ?Sized>(self, exec: &E) -> Result<Collection<R>> {
self.get(exec).await
}
pub(crate) fn bound(self) -> Result<Bound<R>> {
let parent = self.core.parent()?.clone();
let Some(conditions) = self.keys().bound_conditions::<P, R>(&parent)? else {
return Ok(Bound::nothing(self.core.query));
};
let finish = inverse_finisher(&self.inverse, &parent);
Ok(Bound::new(constrain(self.core.query, conditions)).finishing(finish))
}
}
impl<P: Model, R: Model> private::Erase<P> for HasOne<P, R> {
fn erase(self) -> Arc<dyn ErasedRelation<P>> {
let mut unbound = self;
unbound.core = unbound.core.unbound();
Arc::new(unbound)
}
fn rename(&mut self, name: Cow<'static, str>) {
self.core.name = name;
}
}
impl<P: Model, R: Model> private::Erase<P> for HasMany<P, R> {
fn erase(self) -> Arc<dyn ErasedRelation<P>> {
let mut unbound = self;
unbound.core = unbound.core.unbound();
Arc::new(unbound)
}
fn rename(&mut self, name: Cow<'static, str>) {
self.core.name = name;
}
}
impl<P: Model, R: Model> Relation<P> for HasOne<P, R> {
type Value = Option<Record<R>>;
fn name(&self) -> &str {
&self.core.name
}
fn kind(&self) -> RelationKind {
if self.morph.is_some() {
RelationKind::MorphOne
} else {
RelationKind::HasOne
}
}
fn meta(&self) -> RelationMeta {
let mut meta = RelationMeta::new::<P>(&self.core.name, self.kind())
.related::<R>()
.keys(&self.foreign_key, &self.local_key);
meta.morph_type = self.morph.as_ref().map(ToString::to_string);
meta.morph_name = self.morph.as_ref().map(|_| P::morph_name().into_owned());
meta
}
}
impl<P: Model, R: Model> Relation<P> for HasMany<P, R> {
type Value = Collection<R>;
fn name(&self) -> &str {
&self.core.name
}
fn kind(&self) -> RelationKind {
if self.morph.is_some() {
RelationKind::MorphMany
} else {
RelationKind::HasMany
}
}
fn meta(&self) -> RelationMeta {
let mut meta = RelationMeta::new::<P>(&self.core.name, self.kind())
.related::<R>()
.keys(&self.foreign_key, &self.local_key);
meta.morph_type = self.morph.as_ref().map(ToString::to_string);
meta.morph_name = self.morph.as_ref().map(|_| P::morph_name().into_owned());
meta
}
}
impl<P: Model, R: Model> RelatedTo<P> for HasOne<P, R> {
type Related = R;
}
impl<P: Model, R: Model> RelatedTo<P> for HasMany<P, R> {
type Related = R;
}
impl<P: Model, R: Model> ErasedRelation<P> for HasOne<P, R> {
fn name(&self) -> &str {
&self.core.name
}
fn meta(&self) -> RelationMeta {
Relation::meta(self)
}
fn related_type(&self) -> Option<TypeId> {
Some(TypeId::of::<R>())
}
fn eager_load<'a, 'b>(
&'a self,
target: &'a Target<'b>,
parents: &'a mut [Record<P>],
node: &'a EagerNode,
) -> BoxFuture<'a, Result<()>> {
Box::pin(async move {
let relation = constrained(self.clone(), node)?;
let (parent_keys, groups) = self
.keys()
.load(
target,
parents,
relation.core.query,
node,
self.one_of_many.as_ref(),
)
.await?;
let firsts: HashMap<RelationKey, Record<R>> = groups
.into_iter()
.filter_map(|(key, records)| records.into_iter().next().map(|record| (key, record)))
.collect();
let values = distribute(firsts, &parent_keys);
for (parent, value) in parents.iter_mut().zip(values) {
let mut value = value.or_else(|| self.default_for(&parent.model));
if let (Some(inverse), Some(child)) = (&self.inverse, &mut value) {
set_inverse(inverse, parent, std::slice::from_mut(child));
}
parent.relations.set_relation(node.name.clone(), value);
}
Ok(())
})
}
fn exists_query(&self, request: ExistsRequest) -> Result<QueryIr> {
self.keys()
.exists::<P, R>(&self.core.query, request, self.one_of_many.as_ref())
}
fn touch<'a, 'b>(
&'a self,
target: &'a Target<'b>,
parent: &'a Record<P>,
) -> BoxFuture<'a, Result<()>> {
Box::pin(async move {
let mut relation = self.clone();
relation.core.parent = Some(parent.model.clone());
let bound = relation.without_global_scopes().bound()?;
if !bound.empty {
crate::relations::touch::touch_related(Some(bound.query), target).await?;
}
Ok(())
})
}
fn load_nested_missing<'a, 'b>(
&'a self,
target: &'a Target<'b>,
parents: &'a mut [Record<P>],
rest: &'a EagerTree,
) -> BoxFuture<'a, Result<()>> {
Box::pin(crate::relations::lazy::load_nested_one::<P, R>(
target,
parents,
&self.core.name,
rest,
))
}
}
impl<P: Model, R: Model> ErasedRelation<P> for HasMany<P, R> {
fn name(&self) -> &str {
&self.core.name
}
fn meta(&self) -> RelationMeta {
Relation::meta(self)
}
fn related_type(&self) -> Option<TypeId> {
Some(TypeId::of::<R>())
}
fn eager_load<'a, 'b>(
&'a self,
target: &'a Target<'b>,
parents: &'a mut [Record<P>],
node: &'a EagerNode,
) -> BoxFuture<'a, Result<()>> {
Box::pin(async move {
let relation = constrained(self.clone(), node)?;
let (parent_keys, groups) = self
.keys()
.load(target, parents, relation.core.query, node, None)
.await?;
let values = distribute(groups, &parent_keys);
for (parent, value) in parents.iter_mut().zip(values) {
let mut children = value.unwrap_or_default();
if let Some(inverse) = &self.inverse {
set_inverse(inverse, parent, &mut children);
}
parent
.relations
.set_relation(node.name.clone(), Collection::from(children));
}
Ok(())
})
}
fn exists_query(&self, request: ExistsRequest) -> Result<QueryIr> {
self.keys().exists::<P, R>(&self.core.query, request, None)
}
fn touch<'a, 'b>(
&'a self,
target: &'a Target<'b>,
parent: &'a Record<P>,
) -> BoxFuture<'a, Result<()>> {
Box::pin(async move {
let mut relation = self.clone();
relation.core.parent = Some(parent.model.clone());
let bound = relation.without_global_scopes().bound()?;
if !bound.empty {
crate::relations::touch::touch_related(Some(bound.query), target).await?;
}
Ok(())
})
}
fn load_nested_missing<'a, 'b>(
&'a self,
target: &'a Target<'b>,
parents: &'a mut [Record<P>],
rest: &'a EagerTree,
) -> BoxFuture<'a, Result<()>> {
Box::pin(crate::relations::lazy::load_nested_many::<P, R>(
target,
parents,
&self.core.name,
rest,
))
}
}
#[cfg(test)]
mod tests {
use std::fmt::Write as _;
use super::*;
use crate::__doc_models::Activity;
use crate::Dialect;
use crate::relations::keys::in_keys;
fn per_dialect<M: Model>(query: &Builder<M>) -> String {
let mut out = String::new();
for dialect in [Dialect::Postgres, Dialect::MySql, Dialect::Sqlite] {
let statement = query.to_sql(dialect).unwrap();
writeln!(out, "{dialect}: {}", statement.sql).unwrap();
writeln!(out, " values: {:?}", statement.values).unwrap();
}
out
}
#[test]
fn per_parent_limits_number_each_parents_rows() {
let keys = distinct_keys([Value::from("b"), Value::from("a")]);
let query = Builder::<Activity>::new()
.where_(Filter::from(in_keys(
qualified("activities", "deal_id"),
&keys,
)))
.order_by_desc(Activity::DUE_AT)
.offset(1)
.limit(3);
let query = limit_per_parent(query, Expr::Column(qualified("activities", "deal_id")));
insta::assert_snapshot!(per_dialect(&query));
let plain = Builder::<Activity>::new().order_by(Activity::DUE_AT);
let unchanged = limit_per_parent(
plain.clone(),
Expr::Column(qualified("activities", "deal_id")),
);
assert_eq!(
unchanged.to_sql(Dialect::Sqlite).unwrap().sql,
plain.to_sql(Dialect::Sqlite).unwrap().sql
);
}
#[test]
fn nulls_order_inside_the_window_on_every_dialect() {
let query = Builder::<Activity>::new()
.order(Activity::DUE_AT.desc().nulls_last())
.limit(1);
let query = limit_per_parent(query, Expr::Column(qualified("activities", "deal_id")));
insta::assert_snapshot!(per_dialect(&query));
}
}