KogenCredo.Check.Warning.RepoInLoop (KogenCredo v0.1.0)

View Source

Basics

This check is disabled by default.

Learn how to enable it via .credo.exs.

This check has a base priority of low and works with any version of Elixir.

Explanation

A Repo call inside an iteration runs one query per element (N+1).

Bad:

Enum.map(posts, fn post -> Repo.get(User, post.user_id) end)

Good:

users = from(u in User, where: u.id in ^Enum.map(posts, & &1.user_id)) |> Repo.all()

Preload associations, fetch with where ... in ^ids and join in memory, or use Repo.insert_all/update_all for batch writes. Heuristic: loops over small bounded collections are often fine.

Check-Specific Parameters

Use the following parameters to configure this check:

:loop_functions

Enum/Stream function names treated as per-element loops.

This parameter defaults to [:map, :each, :flat_map, :reduce, :reduce_while, :map_reduce, :filter, :reject, :find, :any?, :all?, :sort_by, :group_by, :min_by, :max_by].

:repo_functions

Repo function names that count as a query.

This parameter defaults to [:all, :stream, :one, :one!, :get, :get!, :get_by, :get_by!, :exists?, :aggregate, :preload, :reload, :reload!, :insert, :insert!, :update, :update!, :delete, :delete!, :insert_or_update, :insert_or_update!].

:max_depth

How many local helper calls deep a Repo call is searched (default 3).

This parameter defaults to 3.

:repo_names

Last module segments accepted as a repo (default ["Repo"]).

This parameter defaults to ["Repo"].

:repo_modules

Full repo module names accepted as a repo (strings).

This parameter defaults to [].

:included_paths

Globs of files to check; empty means every file.

This parameter defaults to [].

:excluded_paths

Globs of files to skip (default ["test/**"]).

This parameter defaults to ["test/**"].

General Parameters

Like with all checks, general params can be applied.

Parameters can be configured via the .credo.exs config file.