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
Prefer a single-row Repo read over loading every matching row and taking the first result in Elixir.
Repo.all retrieves and materializes every match even when the caller needs
only one row. Repo.one expresses the cardinality expectation at the Repo
boundary, avoids unnecessary row transfer, and can surface an unexpected
second match instead of silently discarding it.
Examples
Avoid:
query
|> Repo.all()
|> List.first()
query
|> Repo.all()
|> Enum.at(0)
query
|> Repo.all()
|> hd()When the query is expected to return zero or one row, prefer:
Repo.one(query)When the query intentionally selects the first row from an ordered result, preserve that intent in the query:
query
|> Ecto.Query.first()
|> Repo.one()Use the bang variants when a missing row is exceptional. For primary-key
lookups, prefer Repo.get/2 or Repo.get!/2.
Notes
This check uses static AST analysis. It reports direct Repo.all and
first-element selection with List.first/1, Enum.at/2 with the literal
index 0, or hd/1, including piped forms. It cannot infer whether the
caller expects uniqueness or an ordered first row. Other Enum.at/2 indices
are outside this check's scope because they express different offset and
ordering semantics.
Options
This check has no check-specific options. Configure it with an empty option list.
Usage
Add this check to Credo's checks: list in .credo.exs:
%{
configs: [
%{
name: "default",
checks: [
{Bylaw.Credo.Check.Ecto.PreferRepoOneOverAllFirst, []}
]
}
]
}Check-Specific Parameters
There are no specific parameters for this check.
General Parameters
Like with all checks, general params can be applied.
Parameters can be configured via the .credo.exs config file.