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

LegitStack
I’m hoping you guys can give me some general advice and perhaps code examples if you’re feeling up to it. I’m very interested in Elixir,...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
Kagamiiiii
Student & New to elixir. Nice language. I want to convert a english character, e.g. “a”, which is stored in a variable, to it’s asci...
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
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
chrisalley
ExUnit now has describe blocks which is a welcome addition coming from RSpec. In the docs, it states that nested hierarchies of describe ...
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
wernerlaude
In AR this is so simple @articles = current_user.articles How to do in Ecto? def index(conn, _params) do current_user = conn.assig...
New
lucidguppy
I have a super simple question about elixir - how would I take a file like this foo bar baz and output a new file that enumerates th...
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

shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
New
srinivasu
How to handle excepions in elixir? Suppose i have A, B, C ,D, E modules. and each module has get() function. A.get() method will call th...
New
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
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
grych
Hi folks, Few months ago I have announced the proof-of-concept of the library to manipulate the browsers DOM objects directly from Elixi...
639 49522 488
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
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
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
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

We're in Beta

About us Mission Statement