use std::any::Any;
use std::collections::{HashMap, HashSet, VecDeque};
use std::fmt;
use std::marker::PhantomData;
use std::ops::Deref;
use std::sync::Arc;
use id_effect::{Effect, HList, Selector, succeed};
use sea_query::{Condition, Expr, ExprTrait, IntoCondition, Order, Query, Value};
use super::{BoundRepository, Entity, Page, Repository, Run, SqlExecutor, Stmt, and, rows};
use crate::client::SqlClientService;
use crate::error::SqlError;
use crate::from_row::{FromRow, from_rows};
use crate::row::SqlRow;
use crate::value::{SqlValue, ToSqlValue};
pub const MAX_EAGER_DEPTH: usize = 3;
const IN_CHUNK: usize = 1000;
const KEY: &str = "__id_effect_key";
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct FieldMeta {
pub name: &'static str,
pub column: &'static str,
pub schema_type: &'static str,
pub nullable: bool,
pub editable: bool,
pub label: &'static str,
pub relation: Option<&'static str>,
}
impl FieldMeta {
pub const fn new(name: &'static str, column: &'static str, schema_type: &'static str) -> Self {
Self {
name,
column,
schema_type,
nullable: false,
editable: false,
label: name,
relation: None,
}
}
#[must_use]
pub const fn nullable(mut self, nullable: bool) -> Self {
self.nullable = nullable;
self
}
#[must_use]
pub const fn editable(mut self, editable: bool) -> Self {
self.editable = editable;
self
}
#[must_use]
pub const fn label(mut self, label: &'static str) -> Self {
self.label = label;
self
}
#[must_use]
pub const fn relation(mut self, relation: &'static str) -> Self {
self.relation = Some(relation);
self
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum RelationKind {
BelongsTo {
foreign_key: &'static str,
},
HasMany {
foreign_key: &'static str,
},
ManyToMany {
through: &'static str,
local_key: &'static str,
foreign_key: &'static str,
},
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct RelationMeta {
pub name: &'static str,
pub kind: RelationKind,
pub target: &'static str,
pub target_table: &'static str,
}
impl RelationMeta {
pub const fn new(
name: &'static str,
kind: RelationKind,
target: &'static str,
target_table: &'static str,
) -> Self {
Self {
name,
kind,
target,
target_table,
}
}
}
pub struct Relation<P, C> {
name: &'static str,
kind: RelationKind,
nested: Vec<Arc<dyn Loader<C>>>,
entities: PhantomData<fn() -> (P, C)>,
}
impl<P, C> Clone for Relation<P, C> {
fn clone(&self) -> Self {
Self {
name: self.name,
kind: self.kind,
nested: self.nested.clone(),
entities: PhantomData,
}
}
}
impl<P, C> fmt::Debug for Relation<P, C> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Relation")
.field("name", &self.name)
.field("kind", &self.kind)
.field("nested", &self.relations())
.finish()
}
}
impl<P, C> Relation<P, C> {
fn new(name: &'static str, kind: RelationKind) -> Self {
Self {
name,
kind,
nested: Vec::new(),
entities: PhantomData,
}
}
pub fn belongs_to(name: &'static str, foreign_key: &'static str) -> Self {
Self::new(name, RelationKind::BelongsTo { foreign_key })
}
pub fn has_many(name: &'static str, foreign_key: &'static str) -> Self {
Self::new(name, RelationKind::HasMany { foreign_key })
}
pub fn many_to_many(
name: &'static str,
through: &'static str,
local_key: &'static str,
foreign_key: &'static str,
) -> Self {
Self::new(
name,
RelationKind::ManyToMany {
through,
local_key,
foreign_key,
},
)
}
#[inline]
pub fn name(&self) -> &'static str {
self.name
}
#[inline]
pub fn kind(&self) -> RelationKind {
self.kind
}
pub fn relations(&self) -> Vec<&'static str> {
self.nested.iter().map(|l| l.name()).collect()
}
pub fn depth(&self) -> usize {
1 + max_depth(&self.nested)
}
}
impl<P, C: Entity> Relation<P, C> {
#[must_use]
pub fn with<G: Entity + Clone + Sync>(mut self, rel: Relation<C, G>) -> Self {
add_loader(&mut self.nested, rel);
self
}
pub fn meta(&self) -> RelationMeta {
RelationMeta::new(self.name, self.kind, C::NAME, C::TABLE)
}
}
trait Loader<P>: Send + Sync {
fn name(&self) -> &'static str;
fn depth(&self) -> usize;
fn check(&self, repo: &Repository<P>) -> Result<(), SqlError>;
fn load(
&self,
ex: Arc<dyn SqlExecutor>,
repo: &Repository<P>,
parents: Vec<Loaded<P>>,
) -> Effect<Vec<Loaded<P>>, SqlError>;
}
fn max_depth<P>(loaders: &[Arc<dyn Loader<P>>]) -> usize {
loaders.iter().map(|l| l.depth()).max().unwrap_or(0)
}
fn add_loader<P: Entity, C: Entity + Clone + Sync>(
loaders: &mut Vec<Arc<dyn Loader<P>>>,
rel: Relation<P, C>,
) {
loaders.retain(|l| l.name() != rel.name);
loaders.push(Arc::new(rel));
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
struct Key(String);
impl Key {
fn of(value: &SqlValue) -> Self {
Self(value.render())
}
}
impl<P: Entity, C: Entity + Clone + Sync> Relation<P, C> {
fn parent_key(&self, parent: &P) -> Result<Option<SqlValue>, SqlError> {
let RelationKind::BelongsTo { foreign_key } = self.kind else {
return Ok(Some(parent.id().to_sql_value()));
};
match parent
.values()
.into_iter()
.find(|(col, _)| *col == foreign_key)
{
Some((_, SqlValue::Null)) => Ok(None),
Some((_, value)) => Ok(Some(value)),
None => Err(SqlError::Unsupported(format!(
"relation `{}`: entity `{}` has no column `{foreign_key}` (the belongs_to foreign key \
must be a field)",
self.name,
P::NAME
))),
}
}
fn statement(&self, child: &Repository<C>, values: &[SqlValue]) -> Result<Stmt, SqlError> {
let keys = || values.iter().cloned().map(Value::from);
let mut stmt = Query::select();
let key = match self.kind {
RelationKind::ManyToMany {
through,
local_key,
foreign_key,
} => {
let cond = Condition::all().add(Expr::col((through, local_key)).is_in(keys()));
stmt
.columns(C::COLUMNS.iter().map(|col| (C::TABLE, *col)))
.expr_as(Expr::col((through, local_key)), KEY)
.from(C::TABLE)
.inner_join(
through,
Expr::col((through, foreign_key)).equals((C::TABLE, C::ID)),
)
.cond_where(and(child.scope_in(Some(C::TABLE), true)?, cond))
.order_by((C::TABLE, C::ID), Order::Asc);
return child.render(&stmt);
}
RelationKind::HasMany { foreign_key } => foreign_key,
RelationKind::BelongsTo { .. } => C::ID,
};
stmt
.columns(C::COLUMNS.iter().copied())
.expr_as(Expr::col(key), KEY)
.from(C::TABLE);
child.filter(
&mut stmt,
Condition::all().add(Expr::col(key).is_in(keys())),
)?;
stmt.order_by(C::ID, Order::Asc);
child.render(&stmt)
}
fn prepare(
&self,
child: &Repository<C>,
parents: &[Loaded<P>],
) -> Result<(Vec<Option<Key>>, VecDeque<Stmt>), SqlError> {
child.scope(true)?;
let mut keys = Vec::with_capacity(parents.len());
let (mut values, mut seen) = (Vec::new(), HashSet::new());
for parent in parents {
let key = self.parent_key(&parent.entity)?.map(|value| {
let key = Key::of(&value);
if seen.insert(key.clone()) {
values.push(value);
}
key
});
keys.push(key);
}
let stmts = values
.chunks(IN_CHUNK)
.map(|chunk| self.statement(child, chunk))
.collect::<Result<_, _>>()?;
Ok((keys, stmts))
}
}
impl<P: Entity, C: Entity + Clone + Sync> Loader<P> for Relation<P, C> {
fn name(&self) -> &'static str {
self.name
}
fn depth(&self) -> usize {
Relation::depth(self)
}
fn check(&self, repo: &Repository<P>) -> Result<(), SqlError> {
let child = repo.cast::<C>();
child.scope(true)?;
self.nested.iter().try_for_each(|l| l.check(&child))
}
fn load(
&self,
ex: Arc<dyn SqlExecutor>,
repo: &Repository<P>,
parents: Vec<Loaded<P>>,
) -> Effect<Vec<Loaded<P>>, SqlError> {
let child = repo.cast::<C>();
let (keys, stmts) = match self.prepare(&child, &parents) {
Ok(prepared) => prepared,
Err(e) => return id_effect::fail(e),
};
let (name, nested) = (self.name, self.nested.clone());
query_all(Arc::clone(&ex), stmts, Vec::new()).flat_map(move |rows| {
let (owners, children): (Vec<Key>, Vec<Loaded<C>>) = match decode::<C>(&rows) {
Ok(decoded) => decoded.into_iter().unzip(),
Err(e) => return id_effect::fail(e),
};
load_all(ex, child, children, nested.into())
.map(move |children| attach(name, parents, &keys, owners, children))
})
}
}
fn query_all(
ex: Arc<dyn SqlExecutor>,
mut stmts: VecDeque<Stmt>,
mut acc: Vec<SqlRow>,
) -> Effect<Vec<SqlRow>, SqlError> {
let Some((sql, params)) = stmts.pop_front() else {
return succeed(acc);
};
ex.query(&sql, ¶ms).flat_map(move |rows| {
acc.extend(rows);
query_all(ex, stmts, acc)
})
}
fn decode<C: FromRow>(rows: &[SqlRow]) -> Result<Vec<(Key, Loaded<C>)>, SqlError> {
rows
.iter()
.map(|row| Ok((Key::of(row.value(KEY)?), Loaded::new(C::from_row(row)?))))
.collect()
}
fn load_all<P: Entity>(
ex: Arc<dyn SqlExecutor>,
repo: Repository<P>,
parents: Vec<Loaded<P>>,
mut loaders: VecDeque<Arc<dyn Loader<P>>>,
) -> Effect<Vec<Loaded<P>>, SqlError> {
let Some(loader) = loaders.pop_front() else {
return succeed(parents);
};
loader
.load(Arc::clone(&ex), &repo, parents)
.flat_map(move |parents| load_all(ex, repo, parents, loaders))
}
fn attach<P, C: Clone + Send + Sync + 'static>(
name: &'static str,
parents: Vec<Loaded<P>>,
keys: &[Option<Key>],
owners: Vec<Key>,
children: Vec<Loaded<C>>,
) -> Vec<Loaded<P>> {
let mut groups: HashMap<Key, Vec<Loaded<C>>> = HashMap::new();
for (owner, child) in owners.into_iter().zip(children) {
groups.entry(owner).or_default().push(child);
}
let mut uses: HashMap<&Key, usize> = HashMap::new();
for key in keys.iter().flatten() {
*uses.entry(key).or_default() += 1;
}
parents
.into_iter()
.zip(keys)
.map(|(mut parent, key)| {
let children = match key {
None => Vec::new(),
Some(key) => match uses.get_mut(key) {
Some(left) if *left > 1 => {
*left -= 1;
groups.get(key).cloned().unwrap_or_default()
}
_ => groups.remove(key).unwrap_or_default(),
},
};
parent.slots.push(Slot {
name,
children: Arc::new(children),
});
parent
})
.collect()
}
#[derive(Clone)]
struct Slot {
name: &'static str,
children: Arc<dyn Any + Send + Sync>,
}
pub struct Loaded<T> {
entity: T,
slots: Vec<Slot>,
}
impl<T> Loaded<T> {
pub fn new(entity: T) -> Self {
Self {
entity,
slots: Vec::new(),
}
}
#[inline]
pub fn entity(&self) -> &T {
&self.entity
}
#[inline]
pub fn into_entity(self) -> T {
self.entity
}
pub fn get<C: 'static>(&self, rel: &Relation<T, C>) -> &[Loaded<C>] {
self.try_get(rel).unwrap_or(&[])
}
pub fn try_get<C: 'static>(&self, rel: &Relation<T, C>) -> Option<&[Loaded<C>]> {
self
.slots
.iter()
.filter(|slot| slot.name == rel.name)
.find_map(|slot| slot.children.downcast_ref::<Vec<Loaded<C>>>())
.map(Vec::as_slice)
}
pub fn one<C: 'static>(&self, rel: &Relation<T, C>) -> Option<&Loaded<C>> {
self.get(rel).first()
}
pub fn relations(&self) -> Vec<&'static str> {
self.slots.iter().map(|slot| slot.name).collect()
}
}
impl<T> Deref for Loaded<T> {
type Target = T;
fn deref(&self) -> &T {
&self.entity
}
}
impl<T: Clone> Clone for Loaded<T> {
fn clone(&self) -> Self {
Self {
entity: self.entity.clone(),
slots: self.slots.clone(),
}
}
}
impl<T: fmt::Debug> fmt::Debug for Loaded<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Loaded")
.field("entity", &self.entity)
.field("relations", &self.relations())
.finish()
}
}
pub struct EagerRepository<T> {
repo: Repository<T>,
loaders: Vec<Arc<dyn Loader<T>>>,
}
impl<T> Clone for EagerRepository<T> {
fn clone(&self) -> Self {
Self {
repo: self.repo.clone(),
loaders: self.loaders.clone(),
}
}
}
impl<T> fmt::Debug for EagerRepository<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("EagerRepository")
.field("repository", &self.repo)
.field(
"relations",
&self.loaders.iter().map(|l| l.name()).collect::<Vec<_>>(),
)
.finish()
}
}
pub struct BoundEagerRepository<T> {
eager: EagerRepository<T>,
ex: Arc<dyn SqlExecutor>,
}
impl<T> Clone for BoundEagerRepository<T> {
fn clone(&self) -> Self {
Self {
eager: self.eager.clone(),
ex: Arc::clone(&self.ex),
}
}
}
impl<T> fmt::Debug for BoundEagerRepository<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("BoundEagerRepository")
.field(&self.eager)
.finish()
}
}
impl<T: Entity> Repository<T> {
pub fn with<C: Entity + Clone + Sync>(&self, rel: Relation<T, C>) -> EagerRepository<T> {
EagerRepository {
repo: self.clone(),
loaders: Vec::new(),
}
.with(rel)
}
}
impl<T: Entity> BoundRepository<T> {
pub fn with<C: Entity + Clone + Sync>(&self, rel: Relation<T, C>) -> BoundEagerRepository<T> {
BoundEagerRepository {
eager: self.repo.with(rel),
ex: Arc::clone(&self.ex),
}
}
}
impl<T: Entity> EagerRepository<T> {
#[must_use]
pub fn with<C: Entity + Clone + Sync>(mut self, rel: Relation<T, C>) -> Self {
add_loader(&mut self.loaders, rel);
self
}
#[inline]
pub fn repository(&self) -> &Repository<T> {
&self.repo
}
pub fn relations(&self) -> Vec<&'static str> {
self.loaders.iter().map(|l| l.name()).collect()
}
pub fn depth(&self) -> usize {
max_depth(&self.loaders)
}
pub fn on(&self, executor: impl SqlExecutor) -> BoundEagerRepository<T> {
BoundEagerRepository {
eager: self.clone(),
ex: Arc::new(executor),
}
}
fn eager<A: Send + 'static>(
&self,
base: Result<Run<Vec<T>>, SqlError>,
finish: fn(Vec<Loaded<T>>) -> A,
) -> Result<Run<A>, SqlError> {
let depth = self.depth();
if depth > MAX_EAGER_DEPTH {
return Err(SqlError::Unsupported(format!(
"entity `{}`: eager loading nests {depth} relation levels, at most {MAX_EAGER_DEPTH} \
are loaded",
T::NAME
)));
}
self.loaders.iter().try_for_each(|l| l.check(&self.repo))?;
let base = base?;
let (repo, loaders) = (self.repo.clone(), self.loaders.clone());
Ok(Box::new(move |ex| {
base(Arc::clone(&ex)).flat_map(move |rows| {
let parents = rows.into_iter().map(Loaded::new).collect();
load_all(ex, repo, parents, loaders.into()).map(finish)
})
}))
}
fn find_op(&self, id: &T::Id) -> Result<Run<Option<Loaded<T>>>, SqlError> {
let base = self
.repo
.select(Repository::<T>::id_is(id))
.and_then(|mut stmt| self.repo.render(&*stmt.limit(1)))
.map(|stmt| rows(stmt, |rows| from_rows(&rows)));
self.eager(base, |found| found.into_iter().next())
}
fn find_by_op(
&self,
cond: Condition,
page: Option<Page>,
) -> Result<Run<Vec<Loaded<T>>>, SqlError> {
self.eager(self.repo.find_by_op(cond, page), |loaded| loaded)
}
fn load_op(&self, entities: Vec<T>) -> Result<Run<Vec<Loaded<T>>>, SqlError> {
self.eager(Ok(Box::new(move |_| succeed(entities))), |loaded| loaded)
}
}
impl<T: Entity> BoundEagerRepository<T> {
#[must_use]
pub fn with<C: Entity + Clone + Sync>(self, rel: Relation<T, C>) -> Self {
Self {
eager: self.eager.with(rel),
ex: self.ex,
}
}
#[inline]
pub fn eager_repository(&self) -> &EagerRepository<T> {
&self.eager
}
fn run<A: Send + 'static>(&self, op: Result<Run<A>, SqlError>) -> Effect<A, SqlError> {
match op {
Ok(run) => run(Arc::clone(&self.ex)),
Err(e) => id_effect::fail(e),
}
}
}
macro_rules! eager_operations {
($(
$(#[$doc:meta])*
fn $name:ident($($arg:ident: $ty:ty),*) -> $ret:ty = $op:ident($($call:expr),*);
)*) => {
impl<T: Entity> EagerRepository<T> {
$(
$(#[$doc])*
pub fn $name<R, I>(&self, $($arg: $ty),*) -> Effect<$ret, SqlError, R>
where
R: Selector<SqlClientService, I> + HList,
{
Repository::<T>::in_env(self.$op($($call),*))
}
)*
}
impl<T: Entity> BoundEagerRepository<T> {
$(
$(#[$doc])*
pub fn $name(&self, $($arg: $ty),*) -> Effect<$ret, SqlError> {
self.run(self.eager.$op($($call),*))
}
)*
}
};
}
eager_operations! {
fn find(id: T::Id) -> Option<Loaded<T>> = find_op(&id);
fn find_all() -> Vec<Loaded<T>> = find_by_op(Condition::all(), None);
fn find_by(cond: impl IntoCondition) -> Vec<Loaded<T>> =
find_by_op(cond.into_condition(), None);
fn find_page(cond: impl IntoCondition, page: Page) -> Vec<Loaded<T>> =
find_by_op(cond.into_condition(), Some(page));
fn load(entities: Vec<T>) -> Vec<Loaded<T>> = load_op(entities);
}
#[cfg(test)]
mod tests {
use super::*;
use crate::query_builder::Dialect;
#[derive(Clone, Debug, PartialEq)]
struct Order {
id: i64,
customer_id: Option<i64>,
}
impl FromRow for Order {
fn from_row(row: &SqlRow) -> Result<Self, SqlError> {
Ok(Self {
id: row.get("id")?,
customer_id: row.get("customer_id")?,
})
}
}
impl Entity for Order {
type Id = i64;
const NAME: &'static str = "Order";
const TABLE: &'static str = "orders";
const COLUMNS: &'static [&'static str] = &["id", "customer_id"];
const ID: &'static str = "id";
const TENANT: Option<&'static str> = Some("org_id");
fn id(&self) -> i64 {
self.id
}
fn values(&self) -> Vec<(&'static str, SqlValue)> {
vec![
("id", self.id.to_sql_value()),
("customer_id", self.customer_id.to_sql_value()),
]
}
}
#[derive(Clone, Debug, PartialEq)]
struct Tag {
id: i64,
}
impl FromRow for Tag {
fn from_row(row: &SqlRow) -> Result<Self, SqlError> {
Ok(Self { id: row.get("id")? })
}
}
impl Entity for Tag {
type Id = i64;
const NAME: &'static str = "Tag";
const TABLE: &'static str = "tags";
const COLUMNS: &'static [&'static str] = &["id"];
const ID: &'static str = "id";
const SOFT_DELETE: Option<&'static str> = Some("deleted_at");
const TENANT: Option<&'static str> = Some("org_id");
fn id(&self) -> i64 {
self.id
}
fn values(&self) -> Vec<(&'static str, SqlValue)> {
vec![("id", self.id.to_sql_value())]
}
}
fn tags() -> Relation<Order, Tag> {
Relation::many_to_many("tags", "order_tags", "order_id", "tag_id")
}
#[test]
fn defaults_and_metadata() {
assert_eq!(Order::LABEL, "Order");
assert!(Order::FIELDS.is_empty() && Order::RELATIONS.is_empty());
let meta = tags().meta();
assert_eq!(
(meta.name, meta.target, meta.target_table),
("tags", "Tag", "tags")
);
let field = FieldMeta::new("customer_id", "customer_id", "i64")
.nullable(true)
.relation("customer");
assert_eq!(
(field.label, field.nullable, field.editable, field.relation),
("customer_id", true, false, Some("customer"))
);
}
#[test]
fn many_to_many_qualifies_the_child_filters_in_every_dialect() {
let repo = Repository::<Tag>::new(Dialect::Postgres).with_tenant(7i64);
let (sql, params) = tags()
.statement(&repo, &[SqlValue::I64(1), SqlValue::I64(2)])
.unwrap();
assert_eq!(
sql,
r#"SELECT "tags"."id", "order_tags"."order_id" AS "__id_effect_key" FROM "tags" INNER JOIN "order_tags" ON "order_tags"."tag_id" = "tags"."id" WHERE "tags"."org_id" = $1 AND "tags"."deleted_at" IS NULL AND "order_tags"."order_id" IN ($2, $3) ORDER BY "tags"."id" ASC"#
);
assert_eq!(
params,
[SqlValue::I64(7), SqlValue::I64(1), SqlValue::I64(2)]
);
let mysql = Repository::<Tag>::new(Dialect::MySql).with_tenant(7i64);
let (sql, _) = tags().statement(&mysql, &[SqlValue::I64(1)]).unwrap();
assert!(
sql.contains("INNER JOIN `order_tags` ON `order_tags`.`tag_id` = `tags`.`id`"),
"{sql}"
);
let sqlite = Repository::<Tag>::new(Dialect::Sqlite).unscoped();
let (sql, _) = tags().statement(&sqlite, &[SqlValue::I64(1)]).unwrap();
assert!(sql.ends_with(r#"WHERE "order_tags"."order_id" IN (?) ORDER BY "tags"."id" ASC"#));
}
#[test]
fn belongs_to_needs_the_foreign_key_field() {
let rel = Relation::<Order, Tag>::belongs_to("tag", "tag_id");
let err = rel
.parent_key(&Order {
id: 1,
customer_id: None,
})
.unwrap_err();
assert!(
matches!(&err, SqlError::Unsupported(m) if m.contains("has no column `tag_id`")),
"{err:?}"
);
let customer = Relation::<Order, Tag>::belongs_to("customer", "customer_id");
let order = |customer_id| Order { id: 1, customer_id };
assert_eq!(customer.parent_key(&order(None)), Ok(None));
assert_eq!(
customer.parent_key(&order(Some(4))),
Ok(Some(SqlValue::I64(4)))
);
}
#[test]
fn keys_are_chunked_and_deduplicated() {
let repo = Repository::<Tag>::new(Dialect::Sqlite).with_tenant(1i64);
let parents: Vec<_> = (0..2_500)
.map(|i| {
Loaded::new(Order {
id: i % 2_100,
customer_id: None,
})
})
.collect();
let (keys, stmts) = tags().prepare(&repo, &parents).unwrap();
assert_eq!((keys.len(), stmts.len()), (2_500, 3));
assert_eq!(
stmts[2].1.len(),
1 + 100,
"the tenant, then the last 100 keys"
);
let unscoped = Repository::<Tag>::new(Dialect::Sqlite);
assert!(matches!(
tags().prepare(&unscoped, &[]),
Err(SqlError::Unsupported(m)) if m.contains("no tenant")
));
}
#[test]
fn attach_shares_and_moves_children() {
let rel = tags();
let parents = vec![
Loaded::new(Order {
id: 1,
customer_id: None,
}),
Loaded::new(Order {
id: 2,
customer_id: None,
}),
Loaded::new(Order {
id: 1,
customer_id: None,
}),
Loaded::new(Order {
id: 3,
customer_id: None,
}),
];
let key = |n: i64| Key::of(&SqlValue::I64(n));
let keys = [Some(key(1)), Some(key(2)), Some(key(1)), None];
let owners = vec![key(1), key(1), key(2)];
let children = vec![
Loaded::new(Tag { id: 10 }),
Loaded::new(Tag { id: 11 }),
Loaded::new(Tag { id: 12 }),
];
let loaded = attach("tags", parents, &keys, owners, children);
let ids = |o: &Loaded<Order>| o.get(&rel).iter().map(|t| t.id).collect::<Vec<_>>();
assert_eq!(ids(&loaded[0]), [10, 11]);
assert_eq!(ids(&loaded[1]), [12]);
assert_eq!(ids(&loaded[2]), [10, 11], "a shared key clones");
assert_eq!(ids(&loaded[3]), [] as [i64; 0]);
assert_eq!(loaded[3].relations(), ["tags"]);
assert_eq!(loaded[1].one(&rel).map(|t| t.id), Some(12));
let other = Relation::<Order, Order>::has_many("tags", "x");
assert!(
loaded[0].try_get(&other).is_none(),
"a name of another type"
);
let copy = loaded[0].clone();
assert_eq!(copy.entity(), loaded[0].entity());
assert!(format!("{copy:?}").contains("relations: [\"tags\"]"));
assert_eq!(copy.into_entity().id, 1);
}
#[test]
fn relations_nest_debug_and_dedupe() {
let deep = Relation::<Tag, Order>::has_many("orders", "tag_id").with(tags());
assert_eq!((deep.depth(), deep.relations()), (2, vec!["tags"]));
let deep = deep.with(tags());
assert_eq!(deep.relations(), ["tags"], "same name replaces");
assert!(format!("{:?}", deep.clone()).contains("nested: [\"tags\"]"));
let eager = Repository::<Tag>::new(Dialect::Postgres)
.with(deep.clone())
.with(deep);
assert_eq!((eager.relations(), eager.depth()), (vec!["orders"], 2));
assert!(format!("{eager:?}").contains("relations: [\"orders\"]"));
let client: Arc<dyn crate::SqlClient> = Arc::new(crate::TestSqlClient::new());
let bound = eager.on(client);
assert!(format!("{:?}", bound.clone()).starts_with("BoundEagerRepository"));
assert_eq!(bound.eager_repository().relations(), ["orders"]);
assert_eq!(
bound.eager_repository().repository().dialect(),
Dialect::Postgres
);
}
fn failure<A: fmt::Debug + Send + 'static>(eff: Effect<A, SqlError>) -> SqlError {
match eff.block_on() {
id_effect::Exit::Failure(id_effect::Cause::Fail(e)) => e,
other => panic!("expected a failure, got {other:?}"),
}
}
#[test]
fn relation_errors_fail_the_effect() {
let test = crate::TestSqlClient::new();
assert!(matches!(
crate::SqlClient::connect(&test).block_on(),
id_effect::Exit::Success(())
));
let client: Arc<dyn crate::SqlClient> = Arc::new(test.clone());
test.script_query(
r#"SELECT "id", "customer_id" FROM "orders" WHERE "org_id" = $1 ORDER BY "id" ASC"#,
vec![SqlRow::from_pairs([
("id", SqlValue::I64(1)),
("customer_id", SqlValue::I64(2)),
])],
);
let orders = Repository::<Order>::new(Dialect::Postgres).with_tenant(1i64);
let bad = Relation::<Order, Tag>::belongs_to("tag", "tag_id");
let err = failure(orders.on(Arc::clone(&client)).with(bad).find_all());
assert!(matches!(err, SqlError::Unsupported(m) if m.contains("tag_id")));
test.script_query(
r#"SELECT "id", "id" AS "__id_effect_key" FROM "tags" WHERE "org_id" = $1 AND "deleted_at" IS NULL AND "id" IN ($2) ORDER BY "id" ASC"#,
vec![SqlRow::from_pairs([("id", SqlValue::I64(2))])],
);
let tag = Relation::<Order, Tag>::belongs_to("tag", "customer_id");
let err = failure(
orders
.on(Arc::clone(&client))
.with(tags())
.with(tag.clone())
.find_all(),
);
assert_eq!(
err,
SqlError::ColumnNotFound {
column: KEY.to_owned()
}
);
test.fail_queries("down");
let err = failure(orders.on(client).with(tag).find_all());
assert!(matches!(err, SqlError::QueryFailed { .. }), "{err:?}");
}
}