use std::sync::{Arc, Mutex};
use crate::support::on_each_database;
use laravel::config::database::ConnectionConfig;
use laravel::db;
use laravel::model::{
BelongsTo, Faker, Fill, IntoCreate, ModelList, MorphKey, MorphMany, MorphOne, MorphRelation, MorphTo, MorphToMany,
MorphType, MorphedByMany, Relation, create, factory, join_row, joined, model, morph, update,
};
use laravel::testing::prelude::*;
use laravel::time::Timestamp;
use serde_json::json;
#[morph]
pub enum Commentable {
Post(Post),
Video(Video),
}
#[morph]
pub enum Imageable {
Post(Post),
}
#[morph]
pub enum Taggable {
Post(Post),
Video(Video),
}
#[join_row(table = "taggables")]
pub struct Tagging {
pub taggable: MorphKey<Taggable>,
#[default]
pub pinned: bool,
pub created_at: Option<Timestamp>,
}
#[model]
pub struct Tag {
pub id: i64,
pub name: String,
#[morphed_by_many(Tagging::taggable)]
pub posts: MorphedByMany<Post, Tagging>,
#[morphed_by_many(Tagging::taggable)]
pub videos: MorphedByMany<Video>,
}
#[factory(Tag)]
pub struct TagFactory;
impl TagFactory {
fn definition(fake: &mut Faker) -> impl IntoCreate<Tag> {
create!(Tag {
name: fake.unique().word()
})
}
}
#[factory(Video)]
pub struct VideoFactory;
impl VideoFactory {
fn definition(fake: &mut Faker) -> impl IntoCreate<Video> {
create!(Video { name: fake.word() })
}
}
#[factory(Comment)]
pub struct CommentFactory;
impl CommentFactory {
fn definition(fake: &mut Faker) -> impl IntoCreate<Comment> {
create!(Comment {
body: fake.sentence(),
commentable: Video::factory()
})
}
}
#[model]
pub struct User {
pub id: i64,
pub name: String,
}
#[model]
pub struct Post {
pub id: i64,
pub user_id: i64,
pub title: String,
#[belongs_to]
pub user: BelongsTo<User>,
#[morph_many(Comment::commentable)]
pub comments: MorphMany<Comment>,
#[morph_one(Image::imageable)]
pub image: MorphOne<Option<Image>>,
#[morph_to_many(Tagging::taggable)]
pub tags: MorphToMany<Tag, Tagging>,
}
#[model(morph = "clip")]
pub struct Video {
pub id: i64,
pub name: String,
#[morph_many(Comment::commentable)]
pub comments: MorphMany<Comment>,
#[morph_to_many(Tagging::taggable)]
pub tags: MorphToMany<Tag>,
}
#[model]
pub struct Comment {
pub id: i64,
pub body: String,
pub commentable_type: MorphType<Commentable>,
pub commentable_id: i64,
#[morph_to]
pub commentable: MorphTo<Commentable>,
}
#[model]
pub struct Image {
pub id: i64,
pub url: String,
pub imageable_type: Option<MorphType<Imageable>>,
pub imageable_id: Option<i64>,
#[morph_to]
pub imageable: MorphTo<Option<Imageable>>,
}
#[derive(serde::Deserialize)]
pub struct Target {
pub commentable_type: MorphType<Commentable>,
pub commentable_id: i64,
}
#[derive(Fill)]
#[fills(Comment)]
pub struct NewComment {
pub body: String,
}
fn app(connection: ConnectionConfig) -> Application {
Application::configure()
.for_testing(env!("CARGO_MANIFEST_DIR"))
.with_config(move |config, _| {
config.database.default = "app".into();
config.database.add_connection("app", connection);
})
.with_routing(|routing, _| {
routing.web(|route| {
route.scope_bindings().group(|route| {
route.get(
"/posts/{post}/comments/{comment}",
|post: Post, comment: Comment| async move { format!("{}: {}", post.title, comment.body) },
);
route.get(
"/videos/{video}/comments/{comment}",
|video: Video, comment: Comment| async move { format!("{}: {}", video.name, comment.body) },
);
route.get("/posts/{post}/tags/{tag}", |post: Post, tag: Tag| async move {
format!("{}: {}", post.title, tag.name)
});
route.get("/videos/{video}/tags/{tag}", |video: Video, tag: Tag| async move {
format!("{}: {}", video.name, tag.name)
});
route.get("/tags/{tag}/videos/{video}", |tag: Tag, video: Video| async move {
format!("{}: {}", tag.name, video.name)
});
});
route.post("/posts/{post}/tags/{tag}", |post: Post, tag: Tag| async move {
let changes = post.tags().toggle(&tag).await?;
Ok::<_, laravel::Error>(format!(
"attached {:?}, detached {:?}",
changes.attached, changes.detached
))
});
route.get(
"/posts/{post}/bodies/{comment:body}",
|post: Post, comment: Comment| async move { format!("{}: {}", post.title, comment.body) },
);
route.post("/commentables", |Json(target): Json<Target>| async move {
let found = Commentable::find(target.commentable_type, target.commentable_id).await?;
Ok::<_, laravel::Error>(match found {
Some(Commentable::Post(post)) => format!("post {}", post.title),
Some(Commentable::Video(video)) => format!("video {}", video.name),
None => "nothing".to_owned(),
})
});
});
})
.create()
}
async fn seed() -> laravel::Result<()> {
let connection = db::default_connection()?;
connection
.schema()
.create("users", |table| {
table.id();
table.string("name");
})
.await?;
connection
.schema()
.create("posts", |table| {
table.id();
table.big_integer("user_id");
table.string("title");
})
.await?;
connection
.schema()
.create("videos", |table| {
table.id();
table.string("name");
})
.await?;
connection
.schema()
.create("comments", |table| {
table.id();
table.string("body");
table.morphs("commentable");
})
.await?;
connection
.schema()
.create("tags", |table| {
table.id();
table.string("name");
})
.await?;
connection
.schema()
.create("taggables", |table| {
table.big_integer("tag_id");
table.morphs("taggable");
table.boolean("pinned").default(false);
table.timestamp("created_at").nullable();
})
.await?;
connection
.schema()
.create("images", |table| {
table.id();
table.string("url");
table.nullable_morphs("imageable");
})
.await?;
db::table("users")
.insert([db::values! { name: "Taylor" }, db::values! { name: "Abigail" }])
.await?;
db::table("posts")
.insert([
db::values! { user_id: 1, title: "One" },
db::values! { user_id: 2, title: "Two" },
])
.await?;
db::table("videos").insert(db::values! { name: "Intro" }).await?;
db::table("comments")
.insert([
db::values! { body: "a", commentable_type: "post", commentable_id: 1 },
db::values! { body: "b", commentable_type: "post", commentable_id: 1 },
db::values! { body: "c", commentable_type: "post", commentable_id: 2 },
db::values! { body: "d", commentable_type: "clip", commentable_id: 1 },
])
.await?;
db::table("tags")
.insert([
db::values! { name: "rust" },
db::values! { name: "php" },
db::values! { name: "go" },
])
.await?;
db::table("taggables")
.insert([
db::values! { tag_id: 1, taggable_type: "post", taggable_id: 1, pinned: true },
db::values! { tag_id: 2, taggable_type: "post", taggable_id: 1, pinned: false },
db::values! { tag_id: 2, taggable_type: "clip", taggable_id: 1, pinned: false },
])
.await?;
db::table("images")
.insert([
db::values! { url: "one.png", imageable_type: "post", imageable_id: 1 },
db::values! { url: "loose.png", imageable_type: None::<String>, imageable_id: None::<i64> },
])
.await?;
Ok(())
}
async fn orphan() -> laravel::Result<()> {
db::table("comments")
.insert(db::values! { body: "orphan", commentable_type: "post", commentable_id: 99 })
.await?;
Ok(())
}
async fn statements<T>(run: impl AsyncFnOnce() -> laravel::Result<T>) -> laravel::Result<(T, Vec<String>)> {
let statements = Arc::new(Mutex::new(Vec::new()));
let listening = Arc::new(Mutex::new(true));
db::listen({
let statements = Arc::clone(&statements);
let listening = Arc::clone(&listening);
move |query| {
if *listening.lock().unwrap() {
statements.lock().unwrap().push(query.sql.clone());
}
}
});
let result = run().await?;
*listening.lock().unwrap() = false;
let statements = statements.lock().unwrap().clone();
Ok((result, statements))
}
fn targets(comments: &[Comment]) -> Vec<(&str, String)> {
comments
.iter()
.map(|comment| {
let target = match &*comment.commentable {
Commentable::Post(post) => format!("post {} by {}", post.title, post.user.name),
Commentable::Video(video) => format!("video {}", video.name),
};
(comment.body.as_str(), target)
})
.collect()
}
fn bodies(comments: &[Comment]) -> Vec<&str> {
comments.iter().map(|comment| comment.body.as_str()).collect()
}
async fn a_morph_to_loads_each_type_with_one_query_and_each_types_own_relations(
app: Application,
) -> laravel::Result<()> {
app.scope(async || {
seed().await?;
let (comments, sql) = statements(async || {
Comment::query()
.with(Comment::commentable.morph_with(Post::user))
.order_by(Comment::id)
.get()
.await
})
.await?;
assert_eq!(sql.len(), 4, "comments, posts, videos, and the posts' users: {sql:#?}");
assert_eq!(
targets(&comments),
[
("a", "post One by Taylor".to_owned()),
("b", "post One by Taylor".to_owned()),
("c", "post Two by Abigail".to_owned()),
("d", "video Intro".to_owned()),
],
);
let images = Image::query().with(Image::imageable).order_by(Image::id).get().await?;
let posts: Vec<Option<&str>> = images
.iter()
.map(|image| {
image
.imageable
.as_ref()
.map(|Imageable::Post(post)| post.title.as_str())
})
.collect();
assert_eq!(posts, [Some("One"), None], "a NULL morph loads as `None`");
Ok(())
})
.await
}
async fn repeated_and_missing_loads_of_a_morph_to_keep_each_types_relations(app: Application) -> laravel::Result<()> {
app.scope(async || {
seed().await?;
let (comments, sql) = statements(async || {
Comment::query()
.with(Comment::commentable.morph_with(Post::user))
.with(Comment::commentable.query::<Post>(|posts| posts.order_by(Post::id)))
.with(Comment::commentable)
.order_by(Comment::id)
.get()
.await
})
.await?;
assert_eq!(sql.len(), 4, "one load of the relation: {sql:#?}");
assert_eq!(targets(&comments)[0].1, "post One by Taylor");
let mut comments = Comment::query().order_by(Comment::id).get().await?;
comments[..2].load(Comment::commentable).await?;
let ((), sql) =
statements(async || comments.load_missing(Comment::commentable.morph_with(Post::user)).await).await?;
assert_eq!(
sql.len(),
4,
"the posts and video of comments c and d, and every post's user: {sql:#?}"
);
assert_eq!(targets(&comments)[1].1, "post One by Taylor");
assert_eq!(targets(&comments)[3].1, "video Intro");
let mut comment = Comment::find_or_fail(4).await?;
let video = comment.commentable().first().await?;
assert!(matches!(video, Some(Commentable::Video(video)) if video.name == "Intro"));
comment.load(Comment::commentable).await?;
comment.refresh().await?;
assert!(comment.commentable.is_loaded(), "refresh reloads the morph");
Ok(())
})
.await
}
async fn morph_many_and_morph_one_read_only_the_rows_of_the_parents_type(app: Application) -> laravel::Result<()> {
app.scope(async || {
seed().await?;
let posts = Post::query()
.with((Post::comments, Post::image))
.with_count(Post::comments)
.order_by(Post::id)
.get()
.await?;
assert_eq!(
bodies(&posts[0].comments),
["a", "b"],
"video 1's comment isn't post 1's"
);
assert_eq!(posts[0].comments.count(), 2);
assert_eq!(posts[0].image.as_ref().map(|image| image.url.as_str()), Some("one.png"));
assert!(posts[1].image.is_none());
let video = Video::query().with(Video::comments).find_or_fail(1).await?;
assert_eq!(bodies(&video.comments), ["d"]);
let post = Post::find_or_fail(1).await?;
assert_eq!(bodies(&post.comments().order_by(Comment::id).get().await?), ["a", "b"]);
let titles = Post::query().has(Post::comments).pluck(Post::title).await?;
assert_eq!(titles, ["One", "Two"]);
let videos = Video::query().doesnt_have(Video::comments).count().await?;
assert_eq!(videos, 0);
Ok(())
})
.await
}
async fn doesnt_have_where_through_one_type_keeps_parents_that_miss_the_condition(
app: Application,
) -> laravel::Result<()> {
app.scope(async || {
seed().await?;
orphan().await?;
let elsewhere = Comment::query()
.doesnt_have_where(Comment::commentable.of::<Post>(), Post::title.eq("One"))
.order_by(Comment::id)
.get()
.await?;
assert_eq!(
bodies(&elsewhere),
["c", "orphan"],
"as `whereDoesntHaveMorph` does, it keeps post comments only, so video 1's isn't one"
);
let unpinned = Post::query()
.doesnt_have_where(Post::tags, Tagging::pinned.eq(true))
.pluck(Post::title)
.await?;
assert_eq!(unpinned, ["Two"]);
let rustless = Video::query()
.doesnt_have_where(Video::tags, Tag::name.eq("rust"))
.pluck(Video::name)
.await?;
assert_eq!(rustless, ["Intro"], "post 1's `rust` tag isn't video 1's");
let unpinned_on_posts = Tag::query()
.doesnt_have_where(Tag::posts, Tagging::pinned.eq(true))
.order_by(Tag::id)
.pluck(Tag::name)
.await?;
assert_eq!(unpinned_on_posts, ["php", "go"]);
Ok(())
})
.await
}
async fn query_updates_set_morph_columns_and_reach_rows_through_join_rows(app: Application) -> laravel::Result<()> {
app.scope(async || {
seed().await?;
let post = Post::find_or_fail(1).await?;
let video = Video::find_or_fail(1).await?;
assert_eq!(update!(post.comments() { commentable: &video }).await?, 2);
let on_video = Comment::query()
.filter(Comment::commentable.is(&video))
.order_by(Comment::id)
.get()
.await?;
assert_eq!(bodies(&on_video), ["a", "b", "d"]);
assert_eq!(post.comments().count().await?, 0);
let pinned = post.tags().query().filter(Tagging::pinned.eq(true));
assert_eq!(update!(pinned { name: "rustlang" }).await?, 1);
assert_eq!(
update!(video.tags() { name: "hypertext" }).await?,
1,
"video 1's tag, and not post 1's `rust`, which shares video 1's key"
);
let names = Tag::query().order_by(Tag::id).pluck(Tag::name).await?;
assert_eq!(names, ["rustlang", "hypertext", "go"]);
Ok(())
})
.await
}
async fn has_where_through_one_type_filters_as_where_has_morph_does(app: Application) -> laravel::Result<()> {
app.scope(async || {
seed().await?;
orphan().await?;
let on_one = Comment::query()
.has_where(Comment::commentable.of::<Post>(), Post::title.eq("One"))
.order_by(Comment::id)
.get()
.await?;
assert_eq!(bodies(&on_one), ["a", "b"], "video 1 shares post 1's key");
let on_videos = Comment::query().has(Comment::commentable.of::<Video>()).get().await?;
assert_eq!(bodies(&on_videos), ["d"]);
let named = Comment::query()
.filter(
Comment::commentable.of::<Post>().exists_where(Post::title.eq("Two"))
| Comment::commentable.of::<Video>().exists_where(Video::name.eq("Intro")),
)
.order_by(Comment::id)
.get()
.await?;
assert_eq!(bodies(&named), ["c", "d"]);
let existing = Comment::query().has(Comment::commentable).count().await?;
assert_eq!(existing, 4, "the orphan's post is gone");
let orphans = Comment::query().doesnt_have(Comment::commentable).get().await?;
assert_eq!(bodies(&orphans), ["orphan"]);
let orphaned_posts = Comment::query()
.doesnt_have(Comment::commentable.of::<Post>())
.get()
.await?;
assert_eq!(
bodies(&orphaned_posts),
["orphan"],
"as `whereDoesntHaveMorph` does, it keeps only post comments, so video 1's isn't one"
);
let video = Video::find_or_fail(1).await?;
let on_video = Comment::query().filter(Comment::commentable.is(&video)).get().await?;
assert_eq!(bodies(&on_video), ["d"]);
let typed = Comment::query()
.filter(Comment::commentable_type.eq(MorphType::of::<Video>()))
.count()
.await?;
assert_eq!(typed, 1);
let error = Comment::query()
.with(Comment::commentable)
.get()
.await
.expect_err("the orphan's post is gone");
assert!(
error.to_string().contains("Comment::commentable found no row"),
"{error}"
);
Ok(())
})
.await
}
async fn writes_store_the_morph_name_and_key(app: Application) -> laravel::Result<()> {
app.scope(async || {
seed().await?;
let post = Post::find_or_fail(2).await?;
let video = Video::find_or_fail(1).await?;
let through = create!(post.comments() { ..NewComment { body: "e".into() } }).await?;
assert_eq!((through.commentable_type.name(), through.commentable_id), ("post", 2));
let mut direct = create!(Comment {
body: "f",
commentable: &video
})
.await?;
assert_eq!((direct.commentable_type.name(), direct.commentable_id), ("clip", 1));
assert!(matches!(&*direct.commentable, Commentable::Video(held) if held.name == "Intro"));
update!(direct { commentable: &post }).await?;
assert!(direct.commentable_type.is::<Post>());
assert!(matches!(&*direct.commentable, Commentable::Post(held) if held.title == "Two"));
let stored = Comment::find_or_fail(direct.id).await?;
assert_eq!((stored.commentable_type.name(), stored.commentable_id), ("post", 2));
let fresh = Comment::query()
.filter(Comment::commentable.is(&post))
.order_by(Comment::id)
.get()
.await?;
assert_eq!(bodies(&fresh), ["c", "e", "f"]);
Ok(())
})
.await
}
async fn children_created_with_their_parent_hold_it_in_their_morph_to(app: Application) -> laravel::Result<()> {
app.scope(async || {
seed().await?;
let post = create!(Post {
user_id: 1,
title: "Nested",
comments: [Comment { body: "g" }, Comment { body: "h" }],
image: Image { url: "nested.png" }
})
.await?;
for comment in &post.comments {
let Commentable::Post(held) = &*comment.commentable else {
panic!("{} holds {:?}, not its post", comment.body, comment.commentable);
};
assert_eq!(held.title, "Nested");
assert!(
held.comments.try_loaded().is_none(),
"the held parent leaves out its own relations"
);
}
let image = post.image.as_ref().expect("the create holds the image");
assert!(matches!(&*image.imageable, Some(Imageable::Post(held)) if held.id == post.id));
let video = Video::factory()
.has(Video::comments, Comment::factory().count(2))
.create()
.await?;
assert_eq!(video.comments.len(), 2);
for comment in &video.comments {
assert!(matches!(&*comment.commentable, Commentable::Video(held) if held.id == video.id));
}
let through = post.comments().create().body("i").await?;
assert!(
!through.commentable.is_loaded(),
"a create through the relation query holds no parent"
);
Ok(())
})
.await
}
async fn a_type_column_reads_only_the_enums_morph_names(app: Application) -> laravel::Result<()> {
app.scope(async || {
seed().await?;
db::table("comments")
.insert(db::values! { body: "old", commentable_type: "App\\Models\\Post", commentable_id: 1 })
.await?;
let error = Comment::query()
.get()
.await
.expect_err("`App\\Models\\Post` isn't listed");
assert!(
error
.to_string()
.contains("`App\\Models\\Post` isn't a morph name of `Commentable`, which lists `post`, `clip`"),
"{error}"
);
Ok(())
})
.await
}
async fn a_loaded_morph_serializes_as_its_model_without_a_tag(app: Application) -> laravel::Result<()> {
app.scope(async || {
seed().await?;
let comment = Comment::query().with(Comment::commentable).find_or_fail(4).await?;
assert_eq!(
serde_json::to_value(&comment)?,
json!({
"id": 4,
"body": "d",
"commentable_type": "clip",
"commentable_id": 1,
"commentable": { "id": 1, "name": "Intro" },
})
);
let unloaded = serde_json::to_value(comment.without_relations())?;
assert_eq!(unloaded.get("commentable"), None);
Ok(())
})
.await
}
async fn a_nested_binding_scopes_through_morph_many_and_the_parents_type(app: Application) -> laravel::Result<()> {
app.scope(async || seed().await).await?;
app.get("/posts/1/comments/2").await.assert_ok().assert_see("One: b");
app.get("/videos/1/comments/4").await.assert_ok().assert_see("Intro: d");
app.get("/posts/1/comments/4").await.assert_not_found();
app.get("/videos/1/comments/1").await.assert_not_found();
app.get("/posts/2/comments/1").await.assert_not_found();
Ok(())
}
fn names(tags: &[Tag]) -> Vec<&str> {
tags.iter().map(|tag| tag.name.as_str()).collect()
}
async fn taggables() -> laravel::Result<Vec<(String, i64, i64, bool)>> {
let rows = db::query!(
"SELECT taggable_type, taggable_id, tag_id, pinned FROM taggables ORDER BY taggable_type, taggable_id, tag_id"
)
.select_as::<(String, i64, i64, bool)>()
.await?;
Ok(rows)
}
fn row(morph: &str, key: i64, tag: i64, pinned: bool) -> (String, i64, i64, bool) {
(morph.to_owned(), key, tag, pinned)
}
async fn morph_to_many_loads_counts_and_filters_only_the_parents_type(app: Application) -> laravel::Result<()> {
app.scope(async || {
seed().await?;
let (posts, sql) = statements(async || {
Post::query()
.with(Post::tags)
.with_count(Post::tags)
.order_by(Post::id)
.get()
.await
})
.await?;
assert_eq!(sql.len(), 3, "posts, tags, and the count: {sql:#?}");
let tags: Vec<(&str, bool)> = posts[0]
.tags
.iter()
.map(|tag| (tag.name.as_str(), tag.join.pinned))
.collect();
assert_eq!(tags, [("rust", true), ("php", false)], "video 1's tags aren't post 1's");
assert_eq!((posts[0].tags.count(), posts[1].tags.count()), (2, 0));
assert_eq!(posts[0].tags[0].join.taggable.morph().name(), "post");
assert_eq!(
serde_json::to_value(&posts[0].tags[0])?,
json!({ "id": 1, "name": "rust", "join": { "taggable": { "type": "post", "id": 1 }, "pinned": true, "created_at": null } })
);
let video = Video::query().with(Video::tags).find_or_fail(1).await?;
assert_eq!(names(&video.tags), ["php"]);
let tags = Tag::query()
.with((Tag::posts, Tag::videos))
.with_count(Tag::videos)
.order_by(Tag::id)
.get()
.await?;
let linked: Vec<(usize, usize, u64)> = tags
.iter()
.map(|tag| (tag.posts.len(), tag.videos.len(), tag.videos.count()))
.collect();
assert_eq!(linked, [(1, 0, 0), (1, 1, 1), (0, 0, 0)]);
assert_eq!(tags[1].videos[0].name, "Intro");
assert_eq!(Tag::query().has(Tag::videos).pluck(Tag::name).await?, ["php"]);
assert_eq!(Tag::query().doesnt_have(Tag::posts).pluck(Tag::name).await?, ["go"]);
let rusty = Video::query()
.has_where(Video::tags, Tag::name.eq("rust"))
.count()
.await?;
assert_eq!(rusty, 0, "post 1's `rust` tag isn't video 1's");
let pinned = Post::query()
.with(Post::tags.query(|tags| tags.filter(Tagging::pinned.eq(true))))
.find_or_fail(1)
.await?;
assert_eq!(pinned.tags.len(), 1);
let post = Post::find_or_fail(1).await?;
assert_eq!(
names(&post.tags().query().order_by(Tag::id).get().await?),
["rust", "php"]
);
Ok(())
})
.await
}
async fn aggregates_and_count_filters_read_only_the_parents_type(app: Application) -> laravel::Result<()> {
app.scope(async || {
seed().await?;
let posts = Post::query()
.with_count(Post::comments)
.with_max(Post::comments, Comment::body)
.with_exists((Post::image, Post::tags))
.order_by(Post::id)
.get()
.await?;
let values: Vec<(u64, Option<String>, bool, bool)> = posts
.iter()
.map(|post| {
(
post.comments.count(),
post.comments.max(Comment::body),
post.image.exists(),
post.tags.exists(),
)
})
.collect();
assert_eq!(
values,
[
(2, Some("b".to_owned()), true, true),
(1, Some("c".to_owned()), false, false)
],
"video 1's comment `d` isn't post 1's"
);
let mut video = Video::find_or_fail(1).await?;
video.load_min(Video::comments, Comment::body).await?;
video.load_count(Video::tags).await?;
assert_eq!(
(video.comments.min(Comment::body), video.tags.count()),
(Some("d".to_owned()), 1)
);
let discussed = Post::query()
.filter(Post::comments.count().ge(2))
.pluck(Post::title)
.await?;
assert_eq!(discussed, ["One"]);
let quiet = Video::query()
.filter(Video::comments.count().eq(1))
.pluck(Video::name)
.await?;
assert_eq!(quiet, ["Intro"], "post 1's comments don't count for video 1");
let pinned = Post::query()
.filter(Post::tags.count_where(Tagging::pinned.eq(true)).eq(1))
.pluck(Post::title)
.await?;
assert_eq!(pinned, ["One"]);
let shared = Tag::query()
.filter(Tag::posts.count().ge(1) & Tag::videos.count().ge(1))
.pluck(Tag::name)
.await?;
assert_eq!(shared, ["php"]);
Ok(())
})
.await
}
async fn morph_to_many_writes_touch_only_the_parents_rows(app: Application) -> laravel::Result<()> {
app.scope(async || {
seed().await?;
let post = Post::find_or_fail(1).await?;
let video = Video::find_or_fail(1).await?;
let php = Tag::find_or_fail(2).await?;
post.tags()
.update_join_row(&php, joined!(Tagging { pinned: true }))
.await?;
let changes = video.tags().sync([1, 3]).await?;
assert_eq!((changes.attached, changes.detached), (vec![1, 3], vec![2]));
assert_eq!(
taggables().await?,
[
row("clip", 1, 1, false),
row("clip", 1, 3, false),
row("post", 1, 1, true),
row("post", 1, 2, true),
],
"the video's sync left the post's rows, and the post's update left the video's"
);
assert_eq!(post.tags().detach([2]).await?, 1);
let go = Tag::find_or_fail(3).await?;
assert_eq!(go.posts().toggle([1, 2]).await?.attached, [1, 2]);
assert_eq!(go.videos().detach([1]).await?, 1);
let laravel = create!(post.tags() { name: "laravel" }).await?;
post.tags().attach((&php, joined!(Tagging { pinned: true }))).await?;
assert_eq!(
taggables().await?,
[
row("clip", 1, 1, false),
row("post", 1, 1, true),
row("post", 1, 2, true),
row("post", 1, 3, false),
row("post", 1, laravel.id, false),
row("post", 2, 3, false),
],
);
Ok(())
})
.await
}
async fn every_relation_through_a_join_row_writes_its_timestamps(app: Application) -> laravel::Result<()> {
app.scope(async || {
seed().await?;
let post = Post::find_or_fail(2).await?;
let video = Video::find_or_fail(1).await?;
let go = Tag::find_or_fail(3).await?;
post.tags().attach([3]).await?;
video.tags().attach([3]).await?;
go.videos().detach([1]).await?;
go.videos().toggle([1]).await?;
let stamped: Vec<String> = db::table("taggables")
.filter(db::col("tag_id").eq(3) & !db::col("created_at").is_null())
.order_by("taggable_type")
.pluck("taggable_type")
.await?;
assert_eq!(
stamped,
["clip", "post"],
"`MorphToMany<Tag>` and `MorphedByMany<Video>` name `Tagging::taggable`, so they write its `created_at`"
);
Ok(())
})
.await
}
async fn factories_create_through_morph_to_many_and_morphed_by_many(app: Application) -> laravel::Result<()> {
app.scope(async || {
seed().await?;
let video = Video::factory()
.has(Video::tags, Tag::factory().count(2))
.create()
.await?;
assert_eq!(video.tags.len(), 2);
let tag = Tag::factory()
.has(Tag::videos, Video::factory().count(3))
.create()
.await?;
assert_eq!(tag.videos.len(), 3);
let rows = taggables().await?;
let videos = rows
.iter()
.filter(|(morph, key, ..)| morph == "clip" && *key == video.id)
.count();
assert_eq!(videos, 2);
let reloaded = Tag::query().with(Tag::videos).find_or_fail(tag.id).await?;
assert_eq!(reloaded.videos.len(), 3);
Ok(())
})
.await
}
async fn a_morph_to_takes_a_factory_or_a_create_which_is_created_first(app: Application) -> laravel::Result<()> {
app.scope(async || {
seed().await?;
let videos = Video::query().count().await?;
let comment = Comment::factory().create().await?;
assert_eq!(Video::query().count().await?, videos + 1);
assert!(comment.commentable_type.is::<Video>());
assert!(matches!(&*comment.commentable, Commentable::Video(held) if held.id == comment.commentable_id));
let post = Post::find_or_fail(1).await?;
let on_post = create!(Comment::factory() { commentable: &post }).await?;
assert_eq!((on_post.commentable_type.name(), on_post.commentable_id), ("post", 1));
assert_eq!(Video::query().count().await?, videos + 1);
let video = Video::find_or_fail(1).await?;
let recycled = create!(Comment::factory() { body: "late" }).recycle(&video).await?;
assert_eq!(recycled.commentable_id, video.id);
assert_eq!(
Video::query().count().await?,
videos + 1,
"the morph parent is recycled after the overrides"
);
let on_new = create!(Comment {
body: "first!",
commentable: create!(Video { name: "Premiere" })
})
.await?;
let stored = Comment::query()
.with(Comment::commentable)
.find_or_fail(on_new.id)
.await?;
assert!(matches!(&*stored.commentable, Commentable::Video(held) if held.name == "Premiere"));
Ok(())
})
.await
}
async fn a_nested_binding_scopes_through_morph_to_many_and_its_inverse(app: Application) -> laravel::Result<()> {
app.scope(async || seed().await).await?;
app.get("/posts/1/tags/1").await.assert_ok().assert_see("One: rust");
app.get("/videos/1/tags/2").await.assert_ok().assert_see("Intro: php");
app.get("/videos/1/tags/1").await.assert_not_found();
app.get("/posts/1/tags/3").await.assert_not_found();
app.get("/tags/2/videos/1").await.assert_ok().assert_see("php: Intro");
app.get("/tags/1/videos/1").await.assert_not_found();
Ok(())
}
async fn for_gives_every_row_one_parent_through_a_morph_to(app: Application) -> laravel::Result<()> {
app.scope(async || {
seed().await?;
let video = Video::find_or_fail(1).await?;
let on_video = Comment::factory()
.count(3)
.for_(Comment::commentable, &video)
.create()
.await?;
assert!(
on_video
.iter()
.all(|comment| comment.commentable_type.is::<Video>() && comment.commentable_id == video.id)
);
assert!(
on_video
.iter()
.all(|comment| matches!(&*comment.commentable, Commentable::Video(held) if held.id == video.id))
);
let videos = Video::query().count().await?;
let on_new = Comment::factory()
.count(2)
.for_(Comment::commentable, Video::factory())
.create()
.await?;
assert_eq!(
Video::query().count().await?,
videos + 1,
"one video for the rows of the create"
);
assert_eq!(on_new[0].commentable_id, on_new[1].commentable_id);
assert!(on_new[0].commentable_type.is::<Video>());
let post = Post::find_or_fail(2).await?;
let on_post = Comment::factory().for_(Comment::commentable, &post).create().await?;
assert_eq!((on_post.commentable_type.name(), on_post.commentable_id), ("post", 2));
assert_eq!(
Video::query().count().await?,
videos + 1,
"the definition's video isn't created"
);
Ok(())
})
.await
}
async fn has_takes_lists_of_models_and_runs_after_a_create_with_overrides(app: Application) -> laravel::Result<()> {
app.scope(async || {
seed().await?;
let rust = Tag::find_or_fail(1).await?;
let php = Tag::find_or_fail(2).await?;
let by_reference = Video::factory().has(Video::tags, vec![&rust, &php]).create().await?;
let in_array = Video::factory().has(Video::tags, [&rust]).create().await?;
let by_value = Video::factory().has(Video::tags, [php.clone()]).create().await?;
for (video, expected) in [
(&by_reference, vec!["php", "rust"]),
(&in_array, vec!["rust"]),
(&by_value, vec!["php"]),
] {
let mut tags = video.tags().pluck(Tag::name).await?;
tags.sort();
assert_eq!(tags, expected);
}
let video = create!(Video::factory() { name: "Premiere" })
.has(Video::comments, Comment::factory().count(2))
.has(Video::tags, [&rust])
.await?;
assert_eq!(video.name, "Premiere");
assert_eq!(video.comments.len(), 2, "the create holds the comments it created");
let stored = Video::query().with(Video::comments).find_or_fail(video.id).await?;
assert_eq!(stored.comments.len(), 2);
assert_eq!(video.tags().pluck(Tag::name).await?, ["rust"]);
Ok(())
})
.await
}
async fn a_plain_nested_route_binds_any_model_and_a_custom_key_scopes_it(app: Application) -> laravel::Result<()> {
app.scope(async || seed().await).await?;
app.post("/posts/1/tags/3")
.await
.assert_ok()
.assert_see("attached [3], detached []");
app.get("/posts/1/tags/3").await.assert_ok().assert_see("One: go");
app.post("/posts/1/tags/3")
.await
.assert_ok()
.assert_see("attached [], detached [3]");
app.get("/posts/1/tags/3").await.assert_not_found();
app.get("/posts/1/bodies/a").await.assert_ok().assert_see("One: a");
app.get("/posts/1/bodies/d").await.assert_not_found();
Ok(())
}
async fn a_morph_enum_finds_the_model_a_type_and_key_name(app: Application) -> laravel::Result<()> {
app.scope(async || seed().await).await?;
app.scope(async || {
let video = Commentable::find(MorphType::of::<Video>(), 1).await?.expect("video 1");
assert!(matches!(&video, Commentable::Video(held) if held.name == "Intro"));
let mut comment = create!(Comment {
body: "moved",
commentable: &video
})
.await?;
let post = Commentable::find(MorphType::of::<Post>(), 2).await?.expect("post 2");
update!(comment { commentable: &post }).await?;
assert_eq!((comment.commentable_type.name(), comment.commentable_id), ("post", 2));
Ok::<_, laravel::Error>(())
})
.await?;
app.post("/commentables")
.json(json!({ "commentable_type": "post", "commentable_id": 1 }))
.await
.assert_ok()
.assert_see("post One");
app.post("/commentables")
.json(json!({ "commentable_type": "clip", "commentable_id": 1 }))
.await
.assert_ok()
.assert_see("video Intro");
app.post("/commentables")
.json(json!({ "commentable_type": "clip", "commentable_id": 99 }))
.await
.assert_ok()
.assert_see("nothing");
app.post("/commentables")
.json(json!({ "commentable_type": "video", "commentable_id": 1 }))
.await
.assert_status(422);
Ok(())
}
on_each_database! {
a_morph_to_loads_each_type_with_one_query_and_each_types_own_relations => "laravel_morphs_load",
repeated_and_missing_loads_of_a_morph_to_keep_each_types_relations => "laravel_morphs_reload",
morph_many_and_morph_one_read_only_the_rows_of_the_parents_type => "laravel_morphs_many",
has_where_through_one_type_filters_as_where_has_morph_does => "laravel_morphs_has",
doesnt_have_where_through_one_type_keeps_parents_that_miss_the_condition => "laravel_morphs_doesnt_have",
query_updates_set_morph_columns_and_reach_rows_through_join_rows => "laravel_morphs_query_updates",
writes_store_the_morph_name_and_key => "laravel_morphs_writes",
children_created_with_their_parent_hold_it_in_their_morph_to => "laravel_morphs_children",
a_type_column_reads_only_the_enums_morph_names => "laravel_morphs_names",
a_loaded_morph_serializes_as_its_model_without_a_tag => "laravel_morphs_json",
a_nested_binding_scopes_through_morph_many_and_the_parents_type => "laravel_morphs_bindings",
morph_to_many_loads_counts_and_filters_only_the_parents_type => "laravel_morphs_to_many",
morph_to_many_writes_touch_only_the_parents_rows => "laravel_morphs_join_writes",
aggregates_and_count_filters_read_only_the_parents_type => "laravel_morphs_aggregates",
every_relation_through_a_join_row_writes_its_timestamps => "laravel_morphs_join_stamps",
factories_create_through_morph_to_many_and_morphed_by_many => "laravel_morphs_factories",
a_morph_to_takes_a_factory_or_a_create_which_is_created_first => "laravel_morphs_creates",
a_nested_binding_scopes_through_morph_to_many_and_its_inverse => "laravel_morphs_join_bindings",
for_gives_every_row_one_parent_through_a_morph_to => "laravel_morphs_for",
has_takes_lists_of_models_and_runs_after_a_create_with_overrides => "laravel_morphs_has_lists",
a_plain_nested_route_binds_any_model_and_a_custom_key_scopes_it => "laravel_morphs_plain_routes",
a_morph_enum_finds_the_model_a_type_and_key_name => "laravel_morphs_find",
}