Skip to content

Commit b59453f

Browse files
Add ecto_query: :preload option to preload query (#4503)
1 parent 840eedf commit b59453f

File tree

3 files changed

+12
-4
lines changed

3 files changed

+12
-4
lines changed

guides/howtos/Multi tenancy with foreign keys.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ defmodule MyApp.Repo do
2727
@impl true
2828
def prepare_query(_operation, query, opts) do
2929
cond do
30-
opts[:skip_org_id] || opts[:schema_migration] ->
30+
opts[:skip_org_id] || opts[:ecto_query] in [:schema_migrations, :preload] ->
3131
{query, opts}
3232

3333
org_id = opts[:org_id] ->
@@ -44,7 +44,7 @@ Now we can pass `:org_id` to all READ operations, such as `get`, `get_by`, `prel
4444

4545
* if you explicitly set `:skip_org_id` to true, it won't require an `:org_id`. This reduces the odds of a developer forgetting to scope their queries, which can accidentally expose private data to other users
4646

47-
* if the `:schema_migration` option is set. This means the repository operation was issued by Ecto itself when migrating our database and we don't want to apply an `org_id` to them
47+
* if the `:ecto_query` option is set. This means the repository operation was issued by Ecto itself, with value `:schema_migration` when migrating our database, or `:preload` when issuing a preload query, and we don't want to apply an `org_id` to them
4848

4949
Still, setting the `org_id` for every operation is cumbersome and error prone. We will be better served if all operations attempt to set an `org_id`.
5050

lib/ecto/repo/preloader.ex

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,15 @@ defmodule Ecto.Repo.Preloader do
5050
normalize_and_preload_each([struct], repo_name, preloads, opts[:take], %{}, tuplet) |> hd()
5151
end
5252

53-
defp normalize_and_preload_each(structs, repo_name, preloads, take, query_assocs, tuplet) do
53+
defp normalize_and_preload_each(
54+
structs,
55+
repo_name,
56+
preloads,
57+
take,
58+
query_assocs,
59+
{adapter_meta, opts}
60+
) do
61+
tuplet = {adapter_meta, Keyword.put(opts, :ecto_query, :preload)}
5462
preloads = normalize(preloads, take, preloads)
5563
preload_each(structs, repo_name, preloads, query_assocs, tuplet)
5664
rescue

test/ecto/repo_test.exs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2162,7 +2162,7 @@ defmodule Ecto.RepoTest do
21622162

21632163
test "preload" do
21642164
PrepareRepo.preload(%MySchemaWithAssoc{parent_id: 1}, :parent, hello: :world)
2165-
assert_received {:all, query, _}
2165+
assert_received {:all, query, [ecto_query: :preload, hello: :world]}
21662166
assert query.from.source == {"my_parent", Ecto.RepoTest.MyParent}
21672167
end
21682168

0 commit comments

Comments
 (0)