Skip to content

Commit b116bd7

Browse files
committed
feat: add preload_order for has_one (todo: add documentation)
1 parent 8b258e4 commit b116bd7

File tree

3 files changed

+22
-2
lines changed

3 files changed

+22
-2
lines changed

Diff for: integration_test/cases/preload.exs

+15
Original file line numberDiff line numberDiff line change
@@ -605,6 +605,21 @@ defmodule Ecto.Integration.PreloadTest do
605605
assert [%{name: "foo"}, %{name: "bar"}] = post.ordered_users
606606
end
607607

608+
test "custom preload_order (one)" do
609+
post = TestRepo.insert!(%Post{users: [%User{name: "bar"}, %User{name: "foo"}], title: "1"})
610+
611+
TestRepo.insert!(%Comment{text: "1", post_id: post.id})
612+
TestRepo.insert!(%Comment{text: "2", post_id: post.id})
613+
TestRepo.insert!(%Comment{text: "3", post_id: post.id})
614+
615+
post = TestRepo.preload(post, [:first_comment, :last_comment])
616+
617+
# asc
618+
assert %{text: "1"} = post.first_comment
619+
# desc
620+
assert %{text: "3"} = post.last_comment
621+
end
622+
608623
test "custom preload_order with mfa" do
609624
post1 = TestRepo.insert!(%Post{users: [%User{name: "bar"}, %User{name: "foo"}], title: "1"})
610625
post2 = TestRepo.insert!(%Post{users: [%User{name: "baz"}, %User{name: "foz"}], title: "2"})

Diff for: integration_test/support/schemas.exs

+2
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,8 @@ defmodule Ecto.Integration.Post do
4949
has_many :comments, Ecto.Integration.Comment, on_delete: :delete_all, on_replace: :delete
5050
has_many :force_comments, Ecto.Integration.Comment, on_replace: :delete_if_exists
5151
has_many :ordered_comments, Ecto.Integration.Comment, preload_order: [:text]
52+
has_one :first_comment, Ecto.Integration.Comment, preload_order: [asc: :id]
53+
has_one :last_comment, Ecto.Integration.Comment, preload_order: [desc: :id]
5254
# The post<->permalink relationship should be marked as uniq
5355
has_one :permalink, Ecto.Integration.Permalink, on_delete: :delete_all, on_replace: :delete
5456
has_one :force_permalink, Ecto.Integration.Permalink, on_replace: :delete_if_exists

Diff for: lib/ecto/repo/preloader.ex

+5-2
Original file line numberDiff line numberDiff line change
@@ -326,8 +326,11 @@ defmodule Ecto.Repo.Preloader do
326326
end
327327

328328
{:one, _} ->
329-
query
330-
end
329+
case assoc.relationship do
330+
:parent -> query
331+
_ -> add_preload_order(assoc.preload_order, query)
332+
end
333+
end
331334

332335
unzip_ids Ecto.Repo.Queryable.all(repo_name, query, tuplet), [], []
333336
end

0 commit comments

Comments
 (0)