Bylaw.Credo.Check.Ecto.PreferRepoAggregateCount (bylaw_credo v0.4.0)

Copy Markdown 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

Prefer database-side counting over loading rows with Repo.all and counting them in memory.

Repo.all(query) materializes every matching row as an Elixir struct and transfers all of those rows from the database, even when the caller only needs a number. Repo.aggregate(query, :count) asks the database for the count directly, avoiding unnecessary row materialization, network transfer, and application memory usage.

Use Repo.aggregate(query, :count) when the exact number of matching rows is needed. Use Repo.exists?/1 when the caller only needs to know whether at least one row matches: it expresses that intent directly and lets the database answer an existence query without counting every matching row.

Examples

Avoid:

  Repo.all(query) |> Enum.count()
  Enum.count(Repo.all(query))
  query |> Repo.all() |> length()

Prefer:

  Repo.aggregate(query, :count)

Prefer Repo.exists?/1 or not Repo.exists?/1 over comparing Repo.aggregate(query, :count) to 0 or 1 for existence checks. Counting is unnecessary when the result is only used as a boolean, and the existence query can stop after finding the first matching row. Avoid:

  Repo.aggregate(query, :count) > 0
  Repo.aggregate(query, :count) == 0

Prefer:

  Repo.exists?(query)
  not Repo.exists?(query)

Notes

This check uses static AST analysis, so it favors clear source-level patterns over runtime behavior.

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.PreferRepoAggregateCount, []}
      ]
    }
  ]
}

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.