Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add preload_order for has_one #4505

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions integration_test/cases/preload.exs
Original file line number Diff line number Diff line change
Expand Up @@ -605,6 +605,21 @@ defmodule Ecto.Integration.PreloadTest do
assert [%{name: "foo"}, %{name: "bar"}] = post.ordered_users
end

test "custom preload_order (one)" do
post = TestRepo.insert!(%Post{users: [%User{name: "bar"}, %User{name: "foo"}], title: "1"})

TestRepo.insert!(%Comment{text: "1", post_id: post.id})
TestRepo.insert!(%Comment{text: "2", post_id: post.id})
TestRepo.insert!(%Comment{text: "3", post_id: post.id})

post = TestRepo.preload(post, [:first_comment, :last_comment])

# asc
assert %{text: "1"} = post.first_comment
# desc
assert %{text: "3"} = post.last_comment
end

test "custom preload_order with mfa" do
post1 = TestRepo.insert!(%Post{users: [%User{name: "bar"}, %User{name: "foo"}], title: "1"})
post2 = TestRepo.insert!(%Post{users: [%User{name: "baz"}, %User{name: "foz"}], title: "2"})
Expand Down
2 changes: 2 additions & 0 deletions integration_test/support/schemas.exs
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,8 @@ defmodule Ecto.Integration.Post do
has_many :comments, Ecto.Integration.Comment, on_delete: :delete_all, on_replace: :delete
has_many :force_comments, Ecto.Integration.Comment, on_replace: :delete_if_exists
has_many :ordered_comments, Ecto.Integration.Comment, preload_order: [:text]
has_one :first_comment, Ecto.Integration.Comment, preload_order: [asc: :id]
has_one :last_comment, Ecto.Integration.Comment, preload_order: [desc: :id]
# The post<->permalink relationship should be marked as uniq
has_one :permalink, Ecto.Integration.Permalink, on_delete: :delete_all, on_replace: :delete
has_one :force_permalink, Ecto.Integration.Permalink, on_replace: :delete_if_exists
Expand Down
7 changes: 5 additions & 2 deletions lib/ecto/repo/preloader.ex
Original file line number Diff line number Diff line change
Expand Up @@ -326,8 +326,11 @@ defmodule Ecto.Repo.Preloader do
end

{:one, _} ->
query
end
case assoc.relationship do
:parent -> query
_ -> add_preload_order(assoc.preload_order, query)
end
end

unzip_ids Ecto.Repo.Queryable.all(repo_name, query, tuplet), [], []
end
Expand Down
Loading