fix: set tenant context when calling data layers

fix: set `from_many?` if a `has_one` has a `sort` applied

(because there is no other reason to apply a `sort`)
This commit is contained in:
Zach Daniel 2024-06-28 11:13:34 -04:00
parent 675e5b3e41
commit 2d29dab90b
4 changed files with 22 additions and 6 deletions

View file

@ -57,6 +57,7 @@ defmodule Ash.DataLayer.Ets do
:domain,
:distinct,
:distinct_sort,
context: %{},
calculations: [],
aggregates: [],
relationships: %{},
@ -272,6 +273,12 @@ defmodule Ash.DataLayer.Ets do
{:ok, %{query | tenant: tenant}}
end
@doc false
@impl true
def set_context(_resource, query, context) do
{:ok, %{query | context: context}}
end
@doc false
@impl true
def filter(query, filter, _resource) do
@ -357,13 +364,15 @@ defmodule Ash.DataLayer.Ets do
tenant: tenant,
calculations: calculations,
aggregates: aggregates,
domain: domain
domain: domain,
context: context
},
_resource,
parent \\ nil
) do
with {:ok, records} <- get_records(resource, tenant),
{:ok, records} <- filter_matches(records, filter, domain, tenant, parent),
{:ok, records} <-
filter_matches(records, filter, domain, context[:private][:tenant], parent),
records <- Sort.runtime_sort(records, distinct_sort || sort, domain: domain),
records <- Sort.runtime_distinct(records, distinct, domain: domain),
records <- Sort.runtime_sort(records, sort, domain: domain),

View file

@ -2905,11 +2905,16 @@ defmodule Ash.Query do
def data_layer_query(%{resource: resource, domain: domain} = ash_query, opts) do
query = opts[:initial_query] || Ash.DataLayer.resource_to_query(resource, domain)
context = ash_query.context
|> Map.put(:action, ash_query.action)
|> Map.put_new(:private, %{})
|> put_in([:private, :tenant], ash_query.tenant)
with {:ok, query} <-
Ash.DataLayer.set_context(
resource,
query,
Map.put(ash_query.context, :action, ash_query.action)
context
),
{:ok, query} <- add_tenant(query, ash_query),
{:ok, query} <- Ash.DataLayer.select(query, ash_query.select, ash_query.resource),

View file

@ -85,6 +85,9 @@ defmodule Ash.Resource.Relationships.HasOne do
def opt_schema, do: @opt_schema
def transform(relationship) do
{:ok, relationship |> Ash.Resource.Actions.Read.concat_filters()}
{:ok,
relationship
|> Ash.Resource.Actions.Read.concat_filters()
|> Map.put(:from_many?, relationship.from_many? || not is_nil(relationship.sort))}
end
end

View file

@ -323,8 +323,7 @@ defmodule Ash.Actions.MultitenancyTest do
end
test "prior filters are not affected by the addition of a multitenancy attribute", %{
tenant1: tenant1,
tenant2: tenant2
tenant1: tenant1
} do
user1 =
User