#![allow(clippy::empty_enums)]
#![allow(clippy::assert_is_empty)]
use sea_orm::{
entity::prelude::*, sea_query::Table, ActiveValue::Set, Database, DatabaseConnection,
QueryOrder, Schema,
};
use sea_orm_relations_kit::{
morph_target, BelongsToMany, Changes, Key, Morph, MorphTarget, MorphToMany, Morphable,
};
mod post {
use sea_orm::entity::prelude::*;
#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
#[sea_orm(table_name = "posts")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: i32,
pub title: String,
pub published: bool,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {}
impl ActiveModelBehavior for ActiveModel {}
}
mod video {
use sea_orm::entity::prelude::*;
#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
#[sea_orm(table_name = "videos")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: i64,
pub title: String,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {}
impl ActiveModelBehavior for ActiveModel {}
}
mod comment {
use sea_orm::entity::prelude::*;
#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
#[sea_orm(table_name = "comments")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: i32,
pub body: String,
pub approved: bool,
pub commentable_type: String,
pub commentable_id: i64,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {}
impl ActiveModelBehavior for ActiveModel {}
}
mod image {
use sea_orm::entity::prelude::*;
#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
#[sea_orm(table_name = "images")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: i32,
pub url: String,
pub imageable_type: Option<String>,
pub imageable_id: Option<String>,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {}
impl ActiveModelBehavior for ActiveModel {}
}
mod tag {
use sea_orm::entity::prelude::*;
#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
#[sea_orm(table_name = "tags")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: i32,
pub name: String,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {}
impl ActiveModelBehavior for ActiveModel {}
}
mod taggable {
use sea_orm::entity::prelude::*;
#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
#[sea_orm(table_name = "taggables")]
pub struct Model {
#[sea_orm(primary_key, auto_increment = false)]
pub tag_id: i32,
#[sea_orm(primary_key, auto_increment = false)]
pub taggable_type: String,
#[sea_orm(primary_key, auto_increment = false)]
pub taggable_id: i64,
pub position: i32,
pub note: Option<String>,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {}
impl ActiveModelBehavior for ActiveModel {}
}
mod user {
use sea_orm::entity::prelude::*;
#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
#[sea_orm(table_name = "users")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: i32,
pub name: String,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {}
impl ActiveModelBehavior for ActiveModel {}
}
mod role {
use sea_orm::entity::prelude::*;
#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
#[sea_orm(table_name = "roles")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: i32,
pub name: String,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {}
impl ActiveModelBehavior for ActiveModel {}
}
mod role_user {
use sea_orm::entity::prelude::*;
#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
#[sea_orm(table_name = "role_user")]
pub struct Model {
#[sea_orm(primary_key, auto_increment = false)]
pub user_id: i32,
#[sea_orm(primary_key, auto_increment = false)]
pub role_id: i32,
pub note: Option<String>,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {}
impl ActiveModelBehavior for ActiveModel {}
}
impl Morphable for post::Entity {
const MORPH_TYPE: &'static str = "post";
}
impl Morphable for video::Entity {
const MORPH_TYPE: &'static str = "video";
}
const COMMENTABLE: Morph<comment::Entity> = Morph::new(
comment::Column::CommentableType,
comment::Column::CommentableId,
);
const IMAGEABLE: Morph<image::Entity> =
Morph::new(image::Column::ImageableType, image::Column::ImageableId);
const TAGS: MorphToMany<taggable::Entity, tag::Entity> = MorphToMany::new(
Morph::new(taggable::Column::TaggableType, taggable::Column::TaggableId),
taggable::Column::TagId,
)
.ordered_by(taggable::Column::Position);
const ROLES: BelongsToMany<role_user::Entity, role::Entity> =
BelongsToMany::new(role_user::Column::UserId, role_user::Column::RoleId);
morph_target! {
#[derive(Clone, Debug, PartialEq)]
enum Commentable {
Post(post::Entity),
Video(video::Entity),
}
}
morph_target! {
#[derive(Clone, Debug, PartialEq)]
enum PostOnly {
Post(post::Entity),
}
}
async fn db() -> DatabaseConnection {
let url = std::env::var("RELATIONS_KIT_DATABASE_URL")
.unwrap_or_else(|_| "sqlite::memory:".to_string());
let db = Database::connect(&url).await.unwrap();
let schema = Schema::new(db.get_database_backend());
macro_rules! recreate {
($($entity:path),+) => {$(
db.execute(&Table::drop().table($entity).if_exists().to_owned()).await.unwrap();
db.execute(&schema.create_table_from_entity($entity)).await.unwrap();
)+};
}
recreate!(
post::Entity,
video::Entity,
comment::Entity,
image::Entity,
tag::Entity,
taggable::Entity,
user::Entity,
role::Entity,
role_user::Entity
);
db
}
async fn new_post(db: &DatabaseConnection, title: &str, published: bool) -> post::Model {
post::ActiveModel {
title: Set(title.into()),
published: Set(published),
..Default::default()
}
.insert(db)
.await
.unwrap()
}
async fn new_video(db: &DatabaseConnection, title: &str) -> video::Model {
video::ActiveModel {
title: Set(title.into()),
..Default::default()
}
.insert(db)
.await
.unwrap()
}
async fn comment_on<O>(
db: &DatabaseConnection,
owner: &O,
body: &str,
approved: bool,
) -> comment::Model
where
O: ModelTrait<Entity: Morphable> + Sync,
{
let mut comment = comment::ActiveModel {
body: Set(body.into()),
approved: Set(approved),
..Default::default()
};
COMMENTABLE.associate(&mut comment, owner).unwrap();
comment.insert(db).await.unwrap()
}
async fn new_tags(db: &DatabaseConnection, names: &[&str]) -> Vec<tag::Model> {
let mut tags = Vec::new();
for name in names {
tags.push(
tag::ActiveModel {
name: Set((*name).into()),
..Default::default()
}
.insert(db)
.await
.unwrap(),
);
}
tags
}
fn names(tags: &[tag::Model]) -> Vec<&str> {
tags.iter().map(|tag| tag.name.as_str()).collect()
}
fn ids(keys: &[i32]) -> Vec<Key> {
keys.iter().copied().map(Key::from).collect()
}
#[tokio::test]
async fn associate_writes_the_type_and_a_key_converted_to_the_column_type() {
let db = db().await;
let post = new_post(&db, "Hello", true).await;
let comment = comment_on(&db, &post, "Nice", true).await;
assert_eq!(comment.commentable_type, "post");
assert_eq!(comment.commentable_id, i64::from(post.id));
assert_eq!(COMMENTABLE.owner_type(&comment).as_deref(), Some("post"));
assert_eq!(
COMMENTABLE.owner_key(&comment),
Some(Key::Int(post.id.into()))
);
assert!(COMMENTABLE.is_owned_by(&comment, &post));
}
#[tokio::test]
async fn find_for_returns_only_the_children_of_that_owner_and_type() {
let db = db().await;
let post = new_post(&db, "Post", true).await;
let video = new_video(&db, "Video").await;
assert_eq!(
i64::from(post.id),
video.id,
"same key, different owner type"
);
comment_on(&db, &post, "on post", true).await;
comment_on(&db, &video, "on video", true).await;
let on_post = COMMENTABLE.find_for(&post).unwrap().all(&db).await.unwrap();
let on_video = COMMENTABLE
.find_for(&video)
.unwrap()
.all(&db)
.await
.unwrap();
assert_eq!(
on_post.iter().map(|c| c.body.as_str()).collect::<Vec<_>>(),
["on post"]
);
assert_eq!(
on_video.iter().map(|c| c.body.as_str()).collect::<Vec<_>>(),
["on video"]
);
}
#[tokio::test]
async fn find_for_is_a_query_to_filter_and_order_like_morph_one() {
let db = db().await;
let post = new_post(&db, "Post", true).await;
comment_on(&db, &post, "first", true).await;
comment_on(&db, &post, "second", false).await;
let latest = COMMENTABLE
.find_for(&post)
.unwrap()
.order_by_desc(comment::Column::Id)
.one(&db)
.await
.unwrap()
.unwrap();
let approved = COMMENTABLE
.find_for(&post)
.unwrap()
.filter(comment::Column::Approved.eq(true))
.count(&db)
.await
.unwrap();
assert_eq!(latest.body, "second");
assert_eq!(approved, 1);
}
#[tokio::test]
async fn load_for_eager_loads_children_in_the_order_of_the_owners() {
let db = db().await;
let first = new_post(&db, "First", true).await;
let empty = new_post(&db, "Empty", true).await;
let last = new_post(&db, "Last", true).await;
comment_on(&db, &last, "on last", true).await;
comment_on(&db, &first, "on first 1", true).await;
comment_on(&db, &first, "on first 2", false).await;
let loaded = COMMENTABLE
.load_for(&db, &[first.clone(), empty.clone(), last.clone()])
.await
.unwrap();
let approved = COMMENTABLE
.load_for_with(
&db,
&[first, empty, last],
comment::Entity::find().filter(comment::Column::Approved.eq(true)),
)
.await
.unwrap();
let bodies = |lists: &[Vec<comment::Model>]| {
lists
.iter()
.map(|list| list.iter().map(|c| c.body.clone()).collect::<Vec<_>>())
.collect::<Vec<_>>()
};
assert_eq!(
bodies(&loaded),
[vec!["on first 1", "on first 2"], vec![], vec!["on last"]]
);
assert_eq!(
bodies(&approved),
[vec!["on first 1"], vec![], vec!["on last"]]
);
assert!(COMMENTABLE
.load_for::<post::Model, _>(&db, &[])
.await
.unwrap()
.is_empty());
}
#[tokio::test]
async fn count_for_counts_children_including_owners_without_any() {
let db = db().await;
let busy = new_post(&db, "Busy", true).await;
let quiet = new_post(&db, "Quiet", true).await;
comment_on(&db, &busy, "a", true).await;
comment_on(&db, &busy, "b", false).await;
let all = COMMENTABLE
.count_for(&db, &[busy.clone(), quiet.clone()])
.await
.unwrap();
let approved = COMMENTABLE
.count_for_with(
&db,
&[busy, quiet],
comment::Entity::find().filter(comment::Column::Approved.eq(true)),
)
.await
.unwrap();
assert_eq!(all, [2, 0]);
assert_eq!(approved, [1, 0]);
}
#[tokio::test]
async fn delete_for_removes_only_that_owners_children() {
let db = db().await;
let post = new_post(&db, "Post", true).await;
let video = new_video(&db, "Video").await;
comment_on(&db, &post, "a", true).await;
comment_on(&db, &post, "b", true).await;
comment_on(&db, &video, "c", true).await;
assert_eq!(COMMENTABLE.delete_for(&db, &post).await.unwrap(), 2);
assert_eq!(comment::Entity::find().count(&db).await.unwrap(), 1);
}
#[tokio::test]
async fn delete_orphans_removes_children_of_deleted_owners_of_that_type() {
let db = db().await;
let kept = new_post(&db, "Kept", true).await;
let gone = new_post(&db, "Gone", true).await;
let video = new_video(&db, "Video").await;
comment_on(&db, &kept, "kept", true).await;
comment_on(&db, &gone, "orphan", true).await;
comment_on(&db, &video, "video", true).await;
gone.delete(&db).await.unwrap();
assert_eq!(
COMMENTABLE
.delete_orphans::<post::Entity, _>(&db)
.await
.unwrap(),
1
);
let left: Vec<String> = comment::Entity::find()
.order_by_asc(comment::Column::Id)
.all(&db)
.await
.unwrap()
.into_iter()
.map(|c| c.body)
.collect();
assert_eq!(left, ["kept", "video"]);
}
#[tokio::test]
async fn owner_resolves_the_owner_whichever_entity_it_is() {
let db = db().await;
let post = new_post(&db, "Post", true).await;
let video = new_video(&db, "Video").await;
let on_post = comment_on(&db, &post, "a", true).await;
let on_video = comment_on(&db, &video, "b", true).await;
let post_owner: Option<Commentable> = COMMENTABLE.owner(&db, &on_post).await.unwrap();
let video_owner: Option<Commentable> = COMMENTABLE.owner(&db, &on_video).await.unwrap();
assert_eq!(post_owner, Some(Commentable::Post(post)));
assert_eq!(
video_owner.as_ref().map(Commentable::morph_type),
Some("video")
);
assert_eq!(video_owner, Some(Commentable::Video(video)));
assert_eq!(Commentable::morph_types(), ["post", "video"]);
}
#[tokio::test]
async fn load_owners_eager_loads_owners_of_mixed_types_in_order() {
let db = db().await;
let post = new_post(&db, "Post", true).await;
let video = new_video(&db, "Video").await;
let gone = new_post(&db, "Gone", true).await;
let comments = vec![
comment_on(&db, &video, "a", true).await,
comment_on(&db, &post, "b", true).await,
comment_on(&db, &gone, "c", true).await,
comment_on(&db, &post, "d", true).await,
];
gone.delete(&db).await.unwrap();
let owners: Vec<Option<Commentable>> = COMMENTABLE.load_owners(&db, &comments).await.unwrap();
assert_eq!(
owners,
[
Some(Commentable::Video(video)),
Some(Commentable::Post(post.clone())),
None,
Some(Commentable::Post(post)),
]
);
}
#[tokio::test]
async fn an_unknown_morph_type_is_an_error_not_a_silent_none() {
let db = db().await;
let video = new_video(&db, "Video").await;
let comment = comment_on(&db, &video, "a", true).await;
let error = COMMENTABLE
.owner::<PostOnly, _>(&db, &comment)
.await
.unwrap_err();
assert!(
error.to_string().contains("unknown morph type `video`"),
"{error}"
);
assert!(COMMENTABLE
.load_owners::<PostOnly, _>(&db, &[comment])
.await
.is_err());
}
#[tokio::test]
async fn a_nullable_string_morph_matches_integer_keys_and_can_be_cleared() {
let db = db().await;
let post = new_post(&db, "Post", true).await;
let mut image = image::ActiveModel {
url: Set("a.png".into()),
..Default::default()
};
IMAGEABLE.associate(&mut image, &post).unwrap();
let image = image.insert(&db).await.unwrap();
assert_eq!(
image.imageable_id.as_deref(),
Some(post.id.to_string().as_str())
);
assert_eq!(
IMAGEABLE.owner::<PostOnly, _>(&db, &image).await.unwrap(),
Some(PostOnly::Post(post.clone()))
);
assert_eq!(
IMAGEABLE
.load_for(&db, std::slice::from_ref(&post))
.await
.unwrap()[0],
std::slice::from_ref(&image)
);
let mut cleared: image::ActiveModel = image.into();
IMAGEABLE.dissociate(&mut cleared).unwrap();
let cleared = cleared.update(&db).await.unwrap();
assert_eq!((cleared.imageable_type, cleared.imageable_id), (None, None));
let unowned = image::Entity::find().one(&db).await.unwrap().unwrap();
assert_eq!(
IMAGEABLE.owner::<PostOnly, _>(&db, &unowned).await.unwrap(),
None
);
assert_eq!(
IMAGEABLE
.load_owners::<PostOnly, _>(&db, &[unowned])
.await
.unwrap(),
[None]
);
}
#[tokio::test]
async fn owned_by_filters_children_by_their_owners_like_where_has_morph() {
let db = db().await;
let published = new_post(&db, "Published", true).await;
let draft = new_post(&db, "Draft", false).await;
let video = new_video(&db, "Video").await;
comment_on(&db, &published, "on published", true).await;
comment_on(&db, &draft, "on draft", true).await;
comment_on(&db, &video, "on video", true).await;
let bodies = |rows: Vec<comment::Model>| rows.into_iter().map(|c| c.body).collect::<Vec<_>>();
let on_published = comment::Entity::find()
.filter(COMMENTABLE.owned_by(post::Entity::find().filter(post::Column::Published.eq(true))))
.all(&db)
.await
.unwrap();
let not_on_published = comment::Entity::find()
.filter(
COMMENTABLE.not_owned_by(post::Entity::find().filter(post::Column::Published.eq(true))),
)
.all(&db)
.await
.unwrap();
let on_any_post = comment::Entity::find()
.filter(COMMENTABLE.of_type::<post::Entity>())
.count(&db)
.await
.unwrap();
let on_anything = comment::Entity::find()
.filter(COMMENTABLE.of_types(["post", "video"]))
.count(&db)
.await
.unwrap();
assert_eq!(bodies(on_published), ["on published"]);
assert_eq!(bodies(not_on_published), ["on draft"]);
assert_eq!((on_any_post, on_anything), (2, 3));
}
#[tokio::test]
async fn owners_with_and_without_filter_owners_by_their_children_like_where_has() {
let db = db().await;
let approved = new_post(&db, "Approved", true).await;
let pending = new_post(&db, "Pending", true).await;
new_post(&db, "Silent", true).await;
let video = new_video(&db, "Video").await;
assert_eq!(i64::from(pending.id), 2);
comment_on(&db, &approved, "ok", true).await;
comment_on(&db, &pending, "wait", false).await;
comment_on(&db, &video, "video", true).await;
let titles = |rows: Vec<post::Model>| rows.into_iter().map(|p| p.title).collect::<Vec<_>>();
let with_any = post::Entity::find()
.filter(COMMENTABLE.owners_with::<post::Entity>(comment::Entity::find()))
.order_by_asc(post::Column::Id)
.all(&db)
.await
.unwrap();
let with_approved = post::Entity::find()
.filter(COMMENTABLE.owners_with::<post::Entity>(
comment::Entity::find().filter(comment::Column::Approved.eq(true)),
))
.all(&db)
.await
.unwrap();
let without_any = post::Entity::find()
.filter(COMMENTABLE.owners_without::<post::Entity>(comment::Entity::find()))
.all(&db)
.await
.unwrap();
assert_eq!(titles(with_any), ["Approved", "Pending"]);
assert_eq!(titles(with_approved), ["Approved"]);
assert_eq!(titles(without_any), ["Silent"]);
}
#[tokio::test]
async fn attach_adds_tags_in_order_and_skips_ones_already_attached() {
let db = db().await;
let post = new_post(&db, "Post", true).await;
let tags = new_tags(&db, &["rust", "loco", "sea-orm"]).await;
let first = TAGS
.attach(&db, &post, [tags[1].id, tags[0].id])
.await
.unwrap();
let second = TAGS
.attach(&db, &post, [tags[0].id, tags[2].id, tags[2].id])
.await
.unwrap();
assert_eq!(first, ids(&[tags[1].id, tags[0].id]));
assert_eq!(second, ids(&[tags[2].id]));
let attached = TAGS.find_for(&post).unwrap().all(&db).await.unwrap();
assert_eq!(names(&attached), ["loco", "rust", "sea-orm"]);
assert_eq!(
TAGS.keys_for(&db, &post).await.unwrap(),
ids(&[tags[1].id, tags[0].id, tags[2].id])
);
let positions: Vec<i32> = TAGS
.pivots_for(&db, &post)
.await
.unwrap()
.iter()
.map(|pivot| pivot.position)
.collect();
assert_eq!(positions, [1, 2, 3]);
}
#[tokio::test]
async fn tags_of_different_owner_types_with_the_same_key_stay_apart() {
let db = db().await;
let post = new_post(&db, "Post", true).await;
let video = new_video(&db, "Video").await;
let tags = new_tags(&db, &["rust", "go"]).await;
TAGS.attach(&db, &post, [tags[0].id]).await.unwrap();
TAGS.attach(&db, &video, [tags[1].id]).await.unwrap();
assert_eq!(
names(&TAGS.find_for(&post).unwrap().all(&db).await.unwrap()),
["rust"]
);
assert_eq!(
names(&TAGS.find_for(&video).unwrap().all(&db).await.unwrap()),
["go"]
);
}
#[tokio::test]
async fn attach_with_fills_extra_pivot_columns() {
let db = db().await;
let post = new_post(&db, "Post", true).await;
let tags = new_tags(&db, &["rust"]).await;
TAGS.attach_with(&db, &post, [tags[0].id], |pivot| {
pivot.note = Set(Some("main topic".into()));
Ok(())
})
.await
.unwrap();
let pivot = &TAGS.pivots_for(&db, &post).await.unwrap()[0];
assert_eq!(pivot.note.as_deref(), Some("main topic"));
}
#[tokio::test]
async fn detach_and_detach_all_remove_pivot_rows_of_that_owner_only() {
let db = db().await;
let post = new_post(&db, "Post", true).await;
let other = new_post(&db, "Other", true).await;
let tags = new_tags(&db, &["a", "b", "c"]).await;
TAGS.attach(&db, &post, tags.iter().map(|t| t.id))
.await
.unwrap();
TAGS.attach(&db, &other, [tags[0].id]).await.unwrap();
assert_eq!(
TAGS.detach(&db, &post, [tags[0].id, tags[1].id])
.await
.unwrap(),
2
);
assert_eq!(TAGS.detach(&db, &post, Vec::<i32>::new()).await.unwrap(), 0);
assert_eq!(
names(&TAGS.find_for(&post).unwrap().all(&db).await.unwrap()),
["c"]
);
assert_eq!(TAGS.detach_all(&db, &post).await.unwrap(), 1);
assert!(TAGS
.find_for(&post)
.unwrap()
.all(&db)
.await
.unwrap()
.is_empty());
assert_eq!(
names(&TAGS.find_for(&other).unwrap().all(&db).await.unwrap()),
["a"]
);
}
#[tokio::test]
async fn sync_makes_the_list_exact_and_reports_what_changed() {
let db = db().await;
let post = new_post(&db, "Post", true).await;
let tags = new_tags(&db, &["a", "b", "c", "d"]).await;
TAGS.attach(&db, &post, [tags[0].id, tags[1].id, tags[2].id])
.await
.unwrap();
let changes = TAGS
.sync(&db, &post, [tags[3].id, tags[2].id, tags[0].id])
.await
.unwrap();
assert_eq!(
changes,
Changes {
attached: ids(&[tags[3].id]),
detached: ids(&[tags[1].id]),
updated: ids(&[tags[2].id, tags[0].id]),
}
);
assert_eq!(
names(&TAGS.find_for(&post).unwrap().all(&db).await.unwrap()),
["d", "c", "a"]
);
let unchanged = TAGS
.sync(&db, &post, [tags[3].id, tags[2].id, tags[0].id])
.await
.unwrap();
assert_eq!(unchanged, Changes::default());
let cleared = TAGS.sync(&db, &post, Vec::<i32>::new()).await.unwrap();
assert_eq!(cleared.detached.len(), 3);
assert!(TAGS.keys_for(&db, &post).await.unwrap().is_empty());
}
#[tokio::test]
async fn sync_with_fills_only_the_new_rows() {
let db = db().await;
let post = new_post(&db, "Post", true).await;
let tags = new_tags(&db, &["old", "new"]).await;
TAGS.attach(&db, &post, [tags[0].id]).await.unwrap();
TAGS.sync_with(&db, &post, [tags[0].id, tags[1].id], |pivot| {
pivot.note = Set(Some("synced".into()));
Ok(())
})
.await
.unwrap();
let notes: Vec<Option<String>> = TAGS
.pivots_for(&db, &post)
.await
.unwrap()
.into_iter()
.map(|pivot| pivot.note)
.collect();
assert_eq!(notes, [None, Some("synced".into())]);
}
#[tokio::test]
async fn sync_without_detaching_and_toggle() {
let db = db().await;
let post = new_post(&db, "Post", true).await;
let tags = new_tags(&db, &["a", "b", "c"]).await;
TAGS.attach(&db, &post, [tags[0].id]).await.unwrap();
let added = TAGS
.sync_without_detaching(&db, &post, [tags[1].id, tags[0].id])
.await
.unwrap();
assert_eq!(added.attached, ids(&[tags[1].id]));
assert_eq!(
names(&TAGS.find_for(&post).unwrap().all(&db).await.unwrap()),
["a", "b"]
);
let toggled = TAGS
.toggle(&db, &post, [tags[0].id, tags[2].id])
.await
.unwrap();
assert_eq!(toggled.detached, ids(&[tags[0].id]));
assert_eq!(toggled.attached, ids(&[tags[2].id]));
assert_eq!(
names(&TAGS.find_for(&post).unwrap().all(&db).await.unwrap()),
["b", "c"]
);
}
#[tokio::test]
async fn update_pivot_changes_one_pivot_row() {
let db = db().await;
let post = new_post(&db, "Post", true).await;
let tags = new_tags(&db, &["a", "b"]).await;
TAGS.attach(&db, &post, [tags[0].id, tags[1].id])
.await
.unwrap();
let changed = TAGS
.update_pivot(&db, &post, tags[1].id, |update| {
update.col_expr(taggable::Column::Note, Expr::value("featured"))
})
.await
.unwrap();
assert_eq!(changed, 1);
let notes: Vec<Option<String>> = TAGS
.pivots_for(&db, &post)
.await
.unwrap()
.into_iter()
.map(|pivot| pivot.note)
.collect();
assert_eq!(notes, [None, Some("featured".into())]);
}
#[tokio::test]
async fn load_for_and_count_for_eager_load_tags_of_many_owners() {
let db = db().await;
let first = new_post(&db, "First", true).await;
let bare = new_post(&db, "Bare", true).await;
let second = new_post(&db, "Second", true).await;
let tags = new_tags(&db, &["a", "b", "c"]).await;
TAGS.attach(&db, &first, [tags[2].id, tags[0].id])
.await
.unwrap();
TAGS.attach(&db, &second, [tags[0].id]).await.unwrap();
let owners = [first, bare, second];
let loaded = TAGS.load_for(&db, &owners).await.unwrap();
let only_a = TAGS
.load_for_with(
&db,
&owners,
tag::Entity::find().filter(tag::Column::Name.eq("a")),
)
.await
.unwrap();
let counts = TAGS.count_for(&db, &owners).await.unwrap();
let lists =
|lists: &[Vec<tag::Model>]| lists.iter().map(|l| names(l).join(",")).collect::<Vec<_>>();
assert_eq!(lists(&loaded), ["c,a", "", "a"]);
assert_eq!(lists(&only_a), ["a", "", "a"]);
assert_eq!(counts, [2, 0, 1]);
}
#[tokio::test]
async fn owners_with_and_with_all_filter_owners_by_their_tags() {
let db = db().await;
let both = new_post(&db, "Both", true).await;
let rust_only = new_post(&db, "Rust only", true).await;
new_post(&db, "None", true).await;
let video = new_video(&db, "Video").await;
let tags = new_tags(&db, &["rust", "loco"]).await;
TAGS.attach(&db, &both, [tags[0].id, tags[1].id])
.await
.unwrap();
TAGS.attach(&db, &rust_only, [tags[0].id]).await.unwrap();
TAGS.attach(&db, &video, [tags[1].id]).await.unwrap();
let titles = |rows: Vec<post::Model>| rows.into_iter().map(|p| p.title).collect::<Vec<_>>();
let with_loco =
post::Entity::find()
.filter(TAGS.owners_with::<post::Entity>(
tag::Entity::find().filter(tag::Column::Name.eq("loco")),
))
.all(&db)
.await
.unwrap();
let with_both = post::Entity::find()
.filter(
TAGS.owners_with_all::<post::Entity>([tags[0].id, tags[1].id])
.unwrap(),
)
.all(&db)
.await
.unwrap();
let untagged = post::Entity::find()
.filter(TAGS.owners_without::<post::Entity>(tag::Entity::find()))
.all(&db)
.await
.unwrap();
assert_eq!(titles(with_loco), ["Both"]);
assert_eq!(titles(with_both), ["Both"]);
assert_eq!(titles(untagged), ["None"]);
}
#[tokio::test]
async fn morphed_by_many_reads_owners_from_the_tag_side() {
let db = db().await;
let first = new_post(&db, "First", true).await;
let second = new_post(&db, "Second", false).await;
let video = new_video(&db, "Video").await;
let tags = new_tags(&db, &["rust", "unused"]).await;
TAGS.attach(&db, &first, [tags[0].id]).await.unwrap();
TAGS.attach(&db, &second, [tags[0].id]).await.unwrap();
TAGS.attach(&db, &video, [tags[0].id]).await.unwrap();
let posts = TAGS
.owners_of::<post::Entity>(&tags[0])
.unwrap()
.order_by_asc(post::Column::Id)
.all(&db)
.await
.unwrap();
let loaded = TAGS
.load_owners_of::<post::Entity, _>(&db, &tags)
.await
.unwrap();
let counts = TAGS
.count_owners_of::<video::Entity, _>(&db, &tags)
.await
.unwrap();
let used_by_published = tag::Entity::find()
.filter(TAGS.related_of(post::Entity::find().filter(post::Column::Published.eq(true))))
.all(&db)
.await
.unwrap();
assert_eq!(
posts.iter().map(|p| p.title.as_str()).collect::<Vec<_>>(),
["First", "Second"]
);
assert_eq!(loaded.iter().map(Vec::len).collect::<Vec<_>>(), [2, 0]);
assert_eq!(counts, [1, 0]);
assert_eq!(names(&used_by_published), ["rust"]);
}
#[tokio::test]
async fn pivot_delete_orphans_cleans_up_after_deleted_owners() {
let db = db().await;
let kept = new_post(&db, "Kept", true).await;
let gone = new_post(&db, "Gone", true).await;
let tags = new_tags(&db, &["a"]).await;
TAGS.attach(&db, &kept, [tags[0].id]).await.unwrap();
TAGS.attach(&db, &gone, [tags[0].id]).await.unwrap();
gone.delete(&db).await.unwrap();
assert_eq!(
TAGS.delete_orphans::<post::Entity, _>(&db).await.unwrap(),
1
);
assert_eq!(taggable::Entity::find().count(&db).await.unwrap(), 1);
}
#[tokio::test]
async fn belongs_to_many_has_the_same_operations_without_a_type_column() {
let db = db().await;
let ann = user::ActiveModel {
name: Set("Ann".into()),
..Default::default()
}
.insert(&db)
.await
.unwrap();
let bob = user::ActiveModel {
name: Set("Bob".into()),
..Default::default()
}
.insert(&db)
.await
.unwrap();
let mut roles = Vec::new();
for name in ["admin", "editor", "viewer"] {
roles.push(
role::ActiveModel {
name: Set(name.into()),
..Default::default()
}
.insert(&db)
.await
.unwrap(),
);
}
ROLES
.attach(&db, &ann, [roles[0].id, roles[1].id])
.await
.unwrap();
ROLES.attach(&db, &bob, [roles[2].id]).await.unwrap();
let changes = ROLES
.sync(&db, &ann, [roles[1].id, roles[2].id])
.await
.unwrap();
ROLES
.update_pivot(&db, &ann, roles[2].id, |update| {
update.col_expr(role_user::Column::Note, Expr::value("temporary"))
})
.await
.unwrap();
assert_eq!(changes.attached, ids(&[roles[2].id]));
assert_eq!(changes.detached, ids(&[roles[0].id]));
assert!(
changes.updated.is_empty(),
"an unordered pivot never reorders"
);
let ann_roles = ROLES
.find_for(&ann)
.unwrap()
.order_by_asc(role::Column::Id)
.all(&db)
.await
.unwrap();
assert_eq!(
ann_roles
.iter()
.map(|r| r.name.as_str())
.collect::<Vec<_>>(),
["editor", "viewer"]
);
assert_eq!(
ROLES
.count_for(&db, &[ann.clone(), bob.clone()])
.await
.unwrap(),
[2, 1]
);
let with_viewer = user::Entity::find()
.filter(ROLES.owners_with::<user::Entity>(
role::Entity::find().filter(role::Column::Name.eq("viewer")),
))
.count(&db)
.await
.unwrap();
assert_eq!(with_viewer, 2);
assert!(ROLES
.pivots_for(&db, &ann)
.await
.unwrap()
.iter()
.any(|pivot| pivot.note.as_deref() == Some("temporary")));
}
#[tokio::test]
async fn a_key_that_does_not_fit_the_column_is_an_error_not_a_panic() {
let db = db().await;
let post = new_post(&db, "Post", true).await;
let error = TAGS.attach(&db, &post, ["not-a-number"]).await.unwrap_err();
assert!(error.to_string().contains("does not fit"), "{error}");
let too_big = TAGS.attach(&db, &post, [i64::MAX]).await.unwrap_err();
assert!(too_big.to_string().contains("does not fit"), "{too_big}");
assert!(TAGS.keys_for(&db, &post).await.unwrap().is_empty());
}
#[tokio::test]
async fn the_same_owner_twice_gets_its_rows_twice() {
let db = db().await;
let post = new_post(&db, "Post", true).await;
let tags = new_tags(&db, &["rust"]).await;
TAGS.attach(&db, &post, [tags[0].id]).await.unwrap();
let loaded = TAGS
.load_for(&db, &[post.clone(), post.clone()])
.await
.unwrap();
let owners = TAGS
.load_owners_of::<post::Entity, _>(&db, &[tags[0].clone(), tags[0].clone()])
.await
.unwrap();
assert_eq!(loaded.iter().map(Vec::len).collect::<Vec<_>>(), [1, 1]);
assert_eq!(owners.iter().map(Vec::len).collect::<Vec<_>>(), [1, 1]);
}
#[tokio::test]
async fn count_for_with_ignores_the_order_of_the_given_query() {
let db = db().await;
let post = new_post(&db, "Post", true).await;
comment_on(&db, &post, "a", true).await;
let counts = COMMENTABLE
.count_for_with(
&db,
std::slice::from_ref(&post),
comment::Entity::find().order_by_asc(comment::Column::Id),
)
.await
.unwrap();
assert_eq!(counts, [1]);
}