OeditusCredo.Check.Warning.NPlusOneQuery
(OeditusCredo v0.6.1)
View Source
Basics
This check is disabled by default.
Learn how to enable it via .credo.exs.
This check has a base priority of high and works with any version of Elixir.
Explanation
N+1 query antipattern occurs when iterating over collections and querying the database for each item.
This leads to poor performance. Use Ecto's preload/2 to fetch associations in a single query.
Bad:
users = Repo.all(User)
Enum.map(users, fn user ->
posts = Repo.get_by(Post, user_id: user.id)
{user, posts}
end)Good:
import Ecto.Query
users = User |> preload(:posts) |> Repo.all()
Enum.map(users, fn user -> {user, user.posts} end)Check-Specific Parameters
Use the following parameters to configure this check:
:exclude_test_files
Set to true to skip test files (default: false)
This parameter defaults to nil.
General Parameters
Like with all checks, general params can be applied.
Parameters can be configured via the .credo.exs config file.