coen.bakker

coen.bakker

I have a function get_by_id/1 that returns a database entry and does so correctly (see below). My approach certainly is naive and resulted in verbose code and probably also relatively bad performance.

  def get_by_id(id) do
    draft = Repo.get(Draft, id)
    case draft.type do
      "regular" ->
        query =
          Draft
          |> join(:inner, [d], t in subquery(RegularDraft), on: t.draft_id == d.id)
          |> select_merge([d, t], %{story: t.story})
          |> preload([:authors, :publications])
        Repo.get(query, id)
      "story_starter" ->
        query =
          Draft
          |> join(:inner, [d], t in subquery(StoryStarterDraft), on: t.draft_id == d.id)
          |> select_merge([d, t], %{story: t.story, starter: t.starter})
          |> preload([:authors, :publications])
        Repo.get(query, id)
    end
  end

As you can see, the function first gets draft from the database and then uses a case ... do to dynamically perform a query that is returned from the function. It’s that dynamic subquery that throws me off. Is this where you would use Dynamic queries — Ecto v3.14.0? I have trouble translating the documentation to my use case. Below is my naive attempt at it (that does not work and throws an error).

  def get_by_id(id) do
    query =
      Draft
      |> join(:inner, [d], t in ^type_query(d.type), on: t.draft_id == d.id)
      |> select_merge([d, t], %{story: t.story})
      |> preload([:authors, :publications])

    Repo.get(query, id)
  end

  def type_query("regular") do
    dynamic([t], subquery(RegularDraft))
  end

  def type_query("story_starter") do
    dynamic([t], subquery(StoryStarterDraft))
  end

Showing Posts 1 to 7

JohnnyCurran

JohnnyCurran

It seems like you are switching the module / schema you query based on the draft type. In that case, something like the following could work

module = case draft.type do
  "regular" -> RegularDraft
  "story_starter" -> StoryStarterDraft
end

from(d in Draft,
join: t in subquery(module),
on: t.draft_id == d.id,
where: d.id == ^id,
select: %{story: t.story, starter: t.start}
)
|> Repo.one()
|> Repo.preload([:authors, :publications])

Un-tested, but should be close

coen.bakker

coen.bakker OP

That’s indeed much less verbose. But I reckon the values of fields of a binding in a query are never accessable in that query? So I must, in any case, make a round trip to the database first to get draft.type?

That would make sense to me but I thought that maybe Postgres/Ecto is smarter than I think and can schedule to get the value of a field in some smart way before running the rest of the query.

JohnnyCurran

JohnnyCurran

Oh, duh…I missed that on the first pass. Let me think on it a touch more

JohnnyCurran

JohnnyCurran

One option could be to use a UNION ALL. It’s slightly duplicative but it is a single query. The problem is I don’t see how to use the draft.type binding on the subquery before having retrieved it from the outer query. And we can’t know to query Regular or StoryStarter before we know the draft type.

This makes the assumption that a draft will only ever be one of a regular or story_starter. The Inner join will return zero rows on one of the queries, leaving you with the desired result:

def get_by_id(id)
starter_query =
  from(d in Draft,
    join: t in StoryStarterDraft,
    on: t.draft_id == d.id,
    where: d.id == ^id,
    where: d.type == "story_starter",
    select: %{
      story: t.story,
      starter: t.starter
    }
  )

query = from(d in Draft,
  join: t in RegularDraft,
  on: t.draft_id == d.id,
  where: d.id == ^id,
  where: d.type == "regular",
  select: %{
    story: t.story,
    starter: nil # UNION ALL needs the result sets to be the same width
  },
  union_all: ^starter_query
)

Repo.one(query)
end
coen.bakker

coen.bakker OP

I hadn’t thought of an approach using union_all at all. I’m going to look at it more closely tomorrow.

coen.bakker

coen.bakker OP

I kinda like this approach: allowing passing the type to the function get_by_id/2. Sometimes I might already have the type, so then I can pass it to the function. If not, I can use the get_by_id/1.

  def get_by_id(id) do
    draft = Repo.get(Draft, id)
    get_by_id(id, draft.type)
  end

  def get_by_id(id, type) do
    type_module =
      case type do
        "regular" -> RegularDraft
        "story_starter" -> StoryStarterDraft
      end

    type_fields =
      case type do
        "regular" -> [:story]
        "story_starter" -> [:story, :starter]
      end

    query =
      from d in Draft,
        join: t in subquery(type_module),
        on: t.draft_id == d.id,
        select_merge: map(t, ^type_fields),
        preload: [:authors, :publications]

    Repo.get(query, id)
  end
JohnnyCurran

JohnnyCurran

You could combine these, too:

{type_module, type_fields} =
  case type do
    "regular" -> {RegularDraft, [:story]}
    "story_starter" -> {StoryStarterDraft, [:story, :starter]}
  end

# query

If you sometimes will know the type/id then making an extra (small) query isn’t the end of the world.

— All posts loaded —

Where Next? Top

Trending in Questions Top

RSP87
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
kpanic
Hi everyone, I am toying with the idea of building a “match maker” for giving personal help to people that wants to start coding. I sta...
New
nseaSeb
Hello, I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New
brecabral
Documentation While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New
velrest
So my question is quite simple and i have found no conclusive answer on forum, google or AI. Should we use :erlang.float for Integer to ...
New
asweet-confluent
I recently noticed that Elixir’s Logger defaults its primary log level to :debug when no :logger, :level application configuration is pre...
New
apz
I’m new to elixir and just tried to install the elixirLS extension for VScode(ium) and it is throwing some errors that I would like help ...
New

Other Trending Topics Top

GenericJam
Edit: 2026 May 15 - This post is archived. Mob is alive!! Main docs: mob v0.7.11 — Documentation A bit of explanation for the slightly c...
New
JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
New
mhanberg
Hi everyone! The first release candidate for the Expert language server project is now available! We’ve published a press release detai...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews