#![allow(clippy::assert_is_empty)]
#![allow(clippy::empty_enums)]
use sea_orm::{
entity::prelude::*, sea_query::Table, ActiveValue::Set, Database, DatabaseConnection, Schema,
};
use sea_orm_relations_kit::{
aggregate_related, count_related, count_related_with, exists_related, latest_of_many, of_many,
oldest_of_many, Aggregate, Morph, Morphable, Pick,
};
mod author {
use sea_orm::entity::prelude::*;
#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
#[sea_orm(table_name = "authors")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: i32,
pub name: String,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {
#[sea_orm(has_many = "super::book::Entity")]
Books,
}
impl Related<super::book::Entity> for Entity {
fn to() -> RelationDef {
Relation::Books.def()
}
}
impl ActiveModelBehavior for ActiveModel {}
}
mod book {
use sea_orm::entity::prelude::*;
#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
#[sea_orm(table_name = "books")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: i32,
pub author_id: i32,
pub title: String,
pub price: i32,
pub year: i32,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {
#[sea_orm(
belongs_to = "super::author::Entity",
from = "Column::AuthorId",
to = "super::author::Column::Id"
)]
Author,
}
impl Related<super::author::Entity> for Entity {
fn to() -> RelationDef {
Relation::Author.def()
}
}
impl ActiveModelBehavior for ActiveModel {}
}
mod account {
use sea_orm::entity::prelude::*;
#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
#[sea_orm(table_name = "accounts")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: i32,
pub name: String,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {}
impl Related<super::team::Entity> for Entity {
fn to() -> RelationDef {
super::membership::Relation::Team.def()
}
fn via() -> Option<RelationDef> {
Some(super::membership::Relation::Account.def().rev())
}
}
impl ActiveModelBehavior for ActiveModel {}
}
mod team {
use sea_orm::entity::prelude::*;
#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
#[sea_orm(table_name = "teams")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: i32,
pub name: String,
pub level: i32,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {}
impl ActiveModelBehavior for ActiveModel {}
}
mod membership {
use sea_orm::entity::prelude::*;
#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
#[sea_orm(table_name = "memberships")]
pub struct Model {
#[sea_orm(primary_key, auto_increment = false)]
pub account_id: i32,
#[sea_orm(primary_key, auto_increment = false)]
pub team_id: i32,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {
#[sea_orm(
belongs_to = "super::account::Entity",
from = "Column::AccountId",
to = "super::account::Column::Id"
)]
Account,
#[sea_orm(
belongs_to = "super::team::Entity",
from = "Column::TeamId",
to = "super::team::Column::Id"
)]
Team,
}
impl ActiveModelBehavior for ActiveModel {}
}
mod review {
use sea_orm::entity::prelude::*;
#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
#[sea_orm(table_name = "reviews")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: i32,
pub reviewable_type: String,
pub reviewable_id: i64,
pub stars: i32,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {}
impl ActiveModelBehavior for ActiveModel {}
}
impl Morphable for author::Entity {
const MORPH_TYPE: &'static str = "author";
}
impl Morphable for book::Entity {
const MORPH_TYPE: &'static str = "book";
}
const REVIEWABLE: Morph<review::Entity> =
Morph::new(review::Column::ReviewableType, review::Column::ReviewableId);
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());
for table in [
"reviews",
"memberships",
"teams",
"accounts",
"books",
"authors",
] {
db.execute(&Table::drop().table(table).if_exists().to_owned())
.await
.unwrap();
}
db.execute(&schema.create_table_from_entity(author::Entity))
.await
.unwrap();
db.execute(&schema.create_table_from_entity(book::Entity))
.await
.unwrap();
db.execute(&schema.create_table_from_entity(account::Entity))
.await
.unwrap();
db.execute(&schema.create_table_from_entity(team::Entity))
.await
.unwrap();
db.execute(&schema.create_table_from_entity(membership::Entity))
.await
.unwrap();
db.execute(&schema.create_table_from_entity(review::Entity))
.await
.unwrap();
db
}
async fn new_author(db: &DatabaseConnection, name: &str) -> author::Model {
author::ActiveModel {
name: Set(name.into()),
..Default::default()
}
.insert(db)
.await
.unwrap()
}
async fn new_book(
db: &DatabaseConnection,
author: &author::Model,
title: &str,
price: i32,
year: i32,
) -> book::Model {
book::ActiveModel {
author_id: Set(author.id),
title: Set(title.into()),
price: Set(price),
year: Set(year),
..Default::default()
}
.insert(db)
.await
.unwrap()
}
async fn library(db: &DatabaseConnection) -> Vec<author::Model> {
let ann = new_author(db, "Ann").await;
let bob = new_author(db, "Bob").await;
let cid = new_author(db, "Cid").await;
new_book(db, &ann, "First", 10, 2020).await;
new_book(db, &ann, "Second", 25, 2024).await;
new_book(db, &cid, "Only", 7, 2021).await;
vec![ann, bob, cid]
}
async fn review<O>(db: &DatabaseConnection, owner: &O, stars: i32) -> review::Model
where
O: ModelTrait<Entity: Morphable> + Sync,
{
let mut review = review::ActiveModel {
stars: Set(stars),
..Default::default()
};
REVIEWABLE.associate(&mut review, owner).unwrap();
review.insert(db).await.unwrap()
}
fn titles(books: &[Option<book::Model>]) -> Vec<Option<&str>> {
books
.iter()
.map(|book| book.as_ref().map(|b| b.title.as_str()))
.collect()
}
#[tokio::test]
async fn count_and_exists_follow_the_owner_order() {
let db = db().await;
let authors = library(&db).await;
assert_eq!(
count_related::<book::Entity, _, _>(&db, &authors)
.await
.unwrap(),
[2, 0, 1]
);
assert_eq!(
count_related_with::<book::Entity, _, _>(
&db,
&authors,
book::Entity::find().filter(book::Column::Price.gt(9)),
)
.await
.unwrap(),
[2, 0, 0]
);
assert_eq!(
exists_related::<book::Entity, _, _>(&db, &authors)
.await
.unwrap(),
[true, false, true]
);
assert!(count_related::<book::Entity, author::Model, _>(&db, &[])
.await
.unwrap()
.is_empty());
}
#[tokio::test]
async fn the_belongs_to_side_counts_the_one_parent() {
let db = db().await;
library(&db).await;
let books = book::Entity::find().all(&db).await.unwrap();
assert_eq!(
count_related::<author::Entity, _, _>(&db, &books)
.await
.unwrap(),
[1, 1, 1]
);
}
#[tokio::test]
async fn aggregates_return_none_for_owners_without_rows() {
let db = db().await;
let authors = library(&db).await;
let price = book::Column::Price;
let sum = aggregate_related::<book::Entity, _, _>(&db, &authors, price, Aggregate::Sum)
.await
.unwrap();
let avg = aggregate_related::<book::Entity, _, _>(&db, &authors, price, Aggregate::Avg)
.await
.unwrap();
let min = aggregate_related::<book::Entity, _, _>(&db, &authors, price, Aggregate::Min)
.await
.unwrap();
let max = aggregate_related::<book::Entity, _, _>(&db, &authors, price, Aggregate::Max)
.await
.unwrap();
assert_eq!(sum, [Some(35.0), None, Some(7.0)]);
assert_eq!(avg, [Some(17.5), None, Some(7.0)]);
assert_eq!(min, [Some(10.0), None, Some(7.0)]);
assert_eq!(max, [Some(25.0), None, Some(7.0)]);
}
#[tokio::test]
async fn latest_and_oldest_of_many_pick_one_row_per_owner() {
let db = db().await;
let authors = library(&db).await;
let latest = latest_of_many::<book::Entity, _, _>(&db, &authors, book::Column::Year)
.await
.unwrap();
let oldest = oldest_of_many::<book::Entity, _, _>(&db, &authors, book::Column::Year)
.await
.unwrap();
let priciest = of_many::<book::Entity, _, _>(&db, &authors, book::Column::Price, Pick::Max)
.await
.unwrap();
assert_eq!(titles(&latest), [Some("Second"), None, Some("Only")]);
assert_eq!(titles(&oldest), [Some("First"), None, Some("Only")]);
assert_eq!(titles(&priciest), [Some("Second"), None, Some("Only")]);
}
#[tokio::test]
async fn a_tie_goes_to_the_row_with_the_largest_key_for_latest() {
let db = db().await;
let ann = new_author(&db, "Ann").await;
new_book(&db, &ann, "Earlier insert", 10, 2024).await;
new_book(&db, &ann, "Later insert", 10, 2024).await;
let latest =
latest_of_many::<book::Entity, _, _>(&db, std::slice::from_ref(&ann), book::Column::Year)
.await
.unwrap();
let oldest =
oldest_of_many::<book::Entity, _, _>(&db, std::slice::from_ref(&ann), book::Column::Year)
.await
.unwrap();
assert_eq!(titles(&latest), [Some("Later insert")]);
assert_eq!(titles(&oldest), [Some("Earlier insert")]);
}
#[tokio::test]
async fn relations_through_a_junction_count_and_aggregate_the_related_rows() {
let db = db().await;
let mut accounts = Vec::new();
for name in ["ann", "bob"] {
accounts.push(
account::ActiveModel {
name: Set(name.into()),
..Default::default()
}
.insert(&db)
.await
.unwrap(),
);
}
let mut teams = Vec::new();
for (name, level) in [("core", 3), ("docs", 1), ("ops", 2)] {
teams.push(
team::ActiveModel {
name: Set(name.into()),
level: Set(level),
..Default::default()
}
.insert(&db)
.await
.unwrap(),
);
}
for (account, team) in [(0, 0), (0, 1), (0, 2), (1, 1)] {
membership::ActiveModel {
account_id: Set(accounts[account].id),
team_id: Set(teams[team].id),
}
.insert(&db)
.await
.unwrap();
}
let counts = count_related::<team::Entity, _, _>(&db, &accounts)
.await
.unwrap();
let senior = count_related_with::<team::Entity, _, _>(
&db,
&accounts,
team::Entity::find().filter(team::Column::Level.gte(2)),
)
.await
.unwrap();
let top_level = aggregate_related::<team::Entity, _, _>(
&db,
&accounts,
team::Column::Level,
Aggregate::Max,
)
.await
.unwrap();
let picked =
of_many::<team::Entity, _, _>(&db, &accounts, team::Column::Level, Pick::Max).await;
assert_eq!(counts, [3, 1]);
assert_eq!(senior, [2, 0]);
assert_eq!(top_level, [Some(3.0), Some(1.0)]);
assert!(picked.unwrap_err().to_string().contains("junction"));
}
#[tokio::test]
async fn morph_aggregates_and_picks_stay_within_the_owner_type() {
let db = db().await;
let authors = library(&db).await;
let book = book::Entity::find().one(&db).await.unwrap().unwrap();
assert_eq!(
book.id, authors[0].id,
"a book and an author share the key 1"
);
let first = review(&db, &authors[0], 3).await;
let best = review(&db, &authors[0], 5).await;
review(&db, &authors[2], 4).await;
review(&db, &book, 1).await;
let stars = review::Column::Stars;
let average = REVIEWABLE
.aggregate_for(&db, &authors, stars, Aggregate::Avg)
.await
.unwrap();
let latest = REVIEWABLE
.latest_for(&db, &authors, review::Column::Id)
.await
.unwrap();
let oldest = REVIEWABLE
.oldest_for(&db, &authors, review::Column::Id)
.await
.unwrap();
let lowest = REVIEWABLE
.pick_for(&db, &authors, stars, Pick::Min)
.await
.unwrap();
let star_list = |rows: &[Option<review::Model>]| {
rows.iter()
.map(|r| r.as_ref().map(|r| r.stars))
.collect::<Vec<_>>()
};
assert_eq!(average, [Some(4.0), None, Some(4.0)]);
assert_eq!(latest[0].as_ref(), Some(&best));
assert_eq!(oldest[0].as_ref(), Some(&first));
assert_eq!(star_list(&latest), [Some(5), None, Some(4)]);
assert_eq!(star_list(&lowest), [Some(3), None, Some(4)]);
}