Ash FrameworkAF
Ash Frameworkโ€ข8mo agoโ€ข
17 replies
Mylan Connolly

Controlling tenancy when joining resources in queries

I have been working on a user-facing query builder in my application. I have a resource Atlas.Tracking.Entity that I configured the multitenancy like so:

  multitenancy do
    strategy :context
    global? true
  end


This is so that I can have global entities and tenant-scoped entities. The actual query parsing is a bit complex, but boils down to using ref to set up fields and then assigning criteria. Where it starts to fall apart is that these entities have a parent relationship as well as a children relationship. If I define a field in the query like ref([:parent], :label) it assumes I'm talking about the global entities table and not the entities table on the same tenant as the query I'm building for. This results in an SQL query like the following:

SELECT DISTINCT ON (e0."id")
  -- ...
FROM
  "client_01972299-b456-75f1-a634-7de10674c28b"."entities" AS e0
  LEFT OUTER JOIN "public"."entities" AS e1 ON e0."id" = e1."parent_id"
  LEFT OUTER JOIN "public"."entities" AS e2 ON e0."parent_id" = e2."id"
WHERE
  -- ...


Whereas I'd expect something like:

SELECT DISTINCT ON (e0."id")
  -- ...
FROM
  "client_01972299-b456-75f1-a634-7de10674c28b"."entities" AS e0
  LEFT OUTER JOIN "client_01972299-b456-75f1-a634-7de10674c28b"."entities" AS e1 ON e0."id" = e1."parent_id"
  LEFT OUTER JOIN "client_01972299-b456-75f1-a634-7de10674c28b"."entities" AS e2 ON e0."parent_id" = e2."id"
WHERE
  -- ...


I realize this is probably a bit non-standard, but I was wondering if there's a way that I could assign the tenancy of the joined relationship in the Ash query builder. I'll keep searching the docs in the meantime.

Thanks!
Solution
ok so it looks like I goofed. it's mostly working as described. I might have changed multiple things:

Atlas.Tracking.Entity |> Ash.Query.for_read(:read, %{}, tenant: client) |> Atlas.QueryParser.add_to_query(query) |> Ash.read!()


results in no tenancy being applied

Atlas.Tracking.Entity |> Ash.Query.for_read(:read, %{}, tenant: client) |> Atlas.QueryParser.add_to_query(query) |> Ash.read!(tenant: client)


sorry for the support questions where mostly in the end there seems to be nothing wrong with the library after all
Was this page helpful?