Skip to content

Commit

Permalink
feat: add preload_order for has_one (todo: add documentation)
Browse files Browse the repository at this point in the history
  • Loading branch information
saveman71 committed Sep 3, 2024
1 parent 8b258e4 commit b116bd7
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 2 deletions.
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

0 comments on commit b116bd7

Please sign in to comment.