Polymorphic preload / how to improve composability of queries?

I have a schema with two assoc, both has_one, named app_a and app_b. This schema also have a field app of type string which can contain “a” or “b”.

I can do:

from(q in MySchema, preload: :app_a)

Now, I want something like this pseudo code:

from(q in MySchema, preload: :"app_#{q.app}")

I have implemented it at a collection/struct level with this:

  def preload_app(%MySchema{app: app} = s) do
    fname = :"app_#{app}"
    Repo.preload(s, fname)
  end

But I was wondering if it was possible to do it at the query level as it would improve composability of queries.

Are there MySchemas that would load a record into app_b but have app == a?

If not, I’d probably just preload [:app_a, :app_b].

Yes, MySchema can have multiple app records that can be “inactive”.

At present I do preload everything when using a query, but as data grows, I wanted to know if there was another way to do it better.