mikl

mikl

Ecto dynamic query (with join) uses wrong table qualifier?

So I have this run-of-the-mill data table with some filtering options, and I’m trying to use dynamic queries to filter it, but I can’t figure out how to get Ecto to use the right table placeholders:

The query:

  def list_company_onboarding_status(sort_direction, sort_field, where_params) do
    Repo.all(
      from os in OnboardingStatus,
        join: c in TorskCompany,
        on: os.company_id == c.id,
        select: {os, c},
        where: ^company_onboarding_status_where_query(where_params),
        order_by: [{^sort_direction, ^sort_field}]
    )
  end

and the dynamic where query generator:

defp company_onboarding_status_where_query(params) do
    Enum.reduce(params, dynamic(true), fn
      {:funnel_step, step}, dynamic ->
        dynamic([os], ^dynamic and os.current_funnel_step == ^step)

      {:migration_cluster, nil}, dynamic ->
        dynamic([c], ^dynamic and is_nil(c.migration_cluster))

      {:migration_cluster, value}, dynamic ->
        dynamic([c], ^dynamic and c.migration_cluster == ^value)

      {:migration_charge, nil}, dynamic ->
        dynamic([c], ^dynamic and is_nil(c.migration_charge))

      {:migration_charge, value}, dynamic ->
        dynamic([c], ^dynamic and c.migration_charge == ^value)

      {_, _}, dynamic ->
        # Not a where parameter
        dynamic
    end)
  end

When I run this, the dynamic where function generates something like dynamic([c], true and c.migration_cluster == ^99), but the query is generated with the wrong placeholder, and errors like this:

[error] GenServer #PID<0.1104.0> terminating
** (Ecto.QueryError) lib/marsvin/companies.ex:254: field `migration_cluster` in `where` does not exist in schema Marsvin.Companies.OnboardingStatus in query:

from o0 in Marsvin.Companies.OnboardingStatus,
  join: t1 in Marsvin.Companies.TorskCompany,
  on: o0.company_id == t1.id,
  where: true and o0.migration_cluster == ^99,
  order_by: [desc_nulls_last: o0.newest_change_at],
  select: {o0, t1}

    (elixir 1.11.3) lib/enum.ex:2193: Enum."-reduce/3-lists^foldl/2-0-"/3

The problem is that despite my dynamic part using the c prefix for the where, indicating that it’s a column from the TorskCompany table, not the OnboardingStatus table, the generated query uses the o0 prefix for that column instead of the correct t1, causing the error since it’s looking at the wrong table.

How do I get Ecto to generate the query correctly?

Marked As Solved

mikl

mikl

Ah, I figured it out, the dynamic part has to list both placeholders for Ecto to understand it correctly, like this:

  defp company_onboarding_status_where_query(params) do
    Enum.reduce(params, dynamic(true), fn
      {:funnel_step, step}, dynamic ->
        dynamic([os, c], ^dynamic and os.current_funnel_step == ^step)

      {:migration_cluster, nil}, dynamic ->
        dynamic([os, c], ^dynamic and is_nil(c.migration_cluster))

      {:migration_cluster, value}, dynamic ->
        dynamic([os, c], ^dynamic and c.migration_cluster == ^value)

      {:migration_charge, nil}, dynamic ->
        dynamic([os, c], ^dynamic and is_nil(c.migration_charge))

      {:migration_charge, value}, dynamic ->
        dynamic([os, c], ^dynamic and c.migration_charge == ^value)

      {_, _}, dynamic ->
        # Not a where parameter
        dynamic
    end)
  end

The change here is that every dynamic line now starts with dynamic([os, c] rather than just dynamic([c].

Where Next?

Popular in Questions Top

sergio
In Ruby, I can go: User.find_by(email: "foobar@email.com").update(email: "hello@email.com") How can I do something similar in Elixir? ...
New
dotdotdotPaul
Okay, I'm having a heck of a time trying to figure out how to best handle the validation of belongs_to associations in Ecto. I'm sure I'...
New
pgiesin
This should be a simple problem but I just can’t seem to figure it out. I have a standalone Elixir app that won’t find the database. Dep...
New
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod -- where is this set? Thanks.
New
script
If I have a string “1000 cfu/ml” . I want to remove the characters and / and space . So the string is like this "1000" What is the ...
New
vac
Hi, I'm quite new in Elixir and I'm trying to format a string to a PEM format. I have the certificate value like MIIDBTCCAe2...... and ...
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
qwerescape
Is there a way to get the call stack or stack trace at any point in the code? Not from exceptions, but an expression that returns how the...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers' Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New

Other popular topics Top

pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
itssasanka
Hi all, Trying to get some more clarity over utc_datetime and naive_datetime for Ecto: https://hexdocs.pm/ecto/Ecto.Schema.html#module-...
New
_russellb
I want to try my hand at web scraping. What tools/libraries do I need to use. I’m hoping to turn this into something professional so don’...
New
KronicDeth
Elixir plugin for JetBrain’s IntelliJ Platform (including Rubymine) This is a plugin that adds support for Elixir to JetBrains IntelliJ...
289 35421 110
New
Jim
As a follow up to my earlier question: I have the code compiling and running but not getting a successful login from the rest server. ...
New
lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
script
If I have a string “1000 cfu/ml” . I want to remove the characters and / and space . So the string is like this "1000" What is the ...
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New

We're in Beta

About us Mission Statement