thiagomajesk

thiagomajesk

How to properly filter/ modify preload queries in ecto? (simple preload, join-preload or other)

Hello everyone, I was working on a project and was faced with this problem and I’d like some input from you on the subject. Imagine this scenario:

  • Posts can be published and reviewed.
  • A Post has many Authors associated with it and vice-versa.
  • Authors can review Posts (identified by the reviewer column in the association).
  • Post(s) can be listed with its authors which must have the virtual reviewer flag filled.

schema "posts" do
  field :title, :string
  field :body, :string
  many_to_many :authors, Author, join_through: AuthorPost, on_replace: :delete)
end
schema "authors" do
  field :name, :string
  field :email, :string
  many_to_many :posts, Post, join_through: AuthorPost, on_replace: :delete)
  field :reviewer, virtual: true
end
 @primary_key false
  schema "authors_posts" do
    field :author_id, :integer, primary_key: true
    field :post_id, :integer, primary_key: true
    field :reviewer, :boolean
  end

The way I see there are three ways that we could approach this at first:

  1. Use a preload-join to load authors associated with posts in a single query. This way I can’t fill the reviewer field. Also, I’m aware that it may not be the best option to do a preload-join for has_many and many_to_many associations as explained here:
Repo.all(
  from p in Post, 
  join: a in assoc(p, :authors), 
  preload: [authors: a]
)

  1. Use a “simple” preload without a join, to load authors associated with posts issuing two queries. This suffers the same problem as the first option because I can’t customize how it’s being fetched from the database. It seems though that the query Ecto outputs for this is a little bit more optimized than whatever I’m doing right now:
Repo.all(
  from p in Post,
  preload: [:authors]
)
SELECT a0.*, p1."id" 
FROM "authors" AS a0 
INNER JOIN "posts" AS p1 
ON p1."id" = ANY($1) 
INNER JOIN "authors_posts" AS a2 
ON a2."post_id" = p1."id" 
WHERE (a2."author_id" = a0."id") 
ORDER BY p1."id" [[1, 2, 3, 4, 5, 6, 7, 8, 9]]

  1. Use a custom preload query, to load authors associated with posts issuing two queries. This allows me to better configure how I want to return the Authors, but the query generated seems a little bit too complex if you consider the second option:
query = 
  from a in Author,
  join: ap in AuthorPost,
  on: a.id == ap.author_id,
  select_merge: %{reviewer: ap.reviewer}

Repo.all(
  from p in Post,
  preload: [authors: ^query]
)
SELECT a0.*, p2."id" 
FROM "authors" AS a0 
INNER JOIN "authors_posts" AS a1 
ON a0."id" = a1."author_id" 
INNER JOIN "posts" AS p2 
ON p2."id" = ANY($1) 
INNER JOIN "authors_posts" AS a3 
ON a3."post_id" = p2."id" 
WHERE (a3."author_id" = a0."id") 
ORDER BY p2."id" [[1, 2, 3, 4, 5, 6, 7, 8, 9]]

So, how would you approach doing this, considering that you must retrieve the records through a Post and not loading the associations directly from the database? I figured that this might be a very common use case, in the end, I went with this last option, but I’d like to explore how to better use Ecto for this purpose.

Some things that I’ve learned fiddling with Ecto SQL this week:

  • It seems that Ecto does not support preloading from a subquery (bummer)
  • It seems that Ecto does not let you customize your join queries (only where’s are aloud)
  • Sometimes it may be better to do two queries to preload instead of a preload-join (not so clear in my mind yet tbh)

Marked As Solved

thiagomajesk

thiagomajesk

Update: Regarding my remarks about option 3: I ended up using Ecto’s preload functions to get a more optimized version of the query I needed (more optimized considering what Ecto was generating by default at least).

Where Next?

Popular in Questions Top

Kurisu
For example for a current url like http://localhost:4000/cosmetic/products?_utf8=✓&query=perfume&page=2, I would like to get: ...
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
dblack
I’ve got an issue with an app and I’ve no idea of how to troubleshoot it. I’m hoping someone here might have seen something similar. I p...
New
komlanvi
Hi everyone, I was playing with phoenix liveView but I run into an issue. I have a form and want to validate each input text when the te...
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

Other popular topics Top

sen
Hi All, I set a environment variables in dev.exs , like below code. when i start server, how can i set the ${enable} value? thanks. d...
New
marius95
Hello everyone, I try to use an Javascript Event Handler in my root.html.leex file. Therefore I created a function in the app.js file: ...
New
JeremM34
Hello, how can I check the Phoenix version ? Thanks !
New
JakeBecker
TL;DR: I’ve just released an implementation of Microsoft’s IDE-independent Language Server Protocol for Elixir. It adds language support ...
1144 53690 245
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
Emily
I have VueJS GUIs with the project generated using Webpack. I have Elixir modules that will need to be used by the VueJS GUIs. I forese...
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New

Latest on Elixir Forum

We're in Beta

About us Mission Statement