Print the record count using Phoenix/Ecto from the terminal

796 views Asked by At

On the Rails app, we can print the record count of a database table by a command like this:

rails r "puts User.count"

With my knowledge, if we want the same thing on the Phoenix/Ecto environment, we should run such a command:

mix run -e "IO.puts SampleApp.Repo.aggregate(SampleApp.User, :count, :id)"

That is OK, but is too lengthy for a daily usage. Is there any shorter way?

2

There are 2 answers

0
Stratus3D On BEST ANSWER

Out of the box, there is not.

You can however define a function in the SampleApp module to make it shorter. Something like this should do the trick (I haven't tested this):

defmodule SampleApp do
  ...

  def count(model)
    IO.puts Repo.aggregate(model, :count, :id)
  end
end

Then you can do this:

mix run -e "SampleApp.count(SampleApp.User)"
0
Tsutomu On

Create a file db.count.ex on the lib/mix/tasks directory as follows:

defmodule Mix.Tasks.Db.Count do
  use Mix.Task
  import Mix.Ecto

  @shortdoc "Print the row count of a database table"

  def run(args) do
    [repo|_] = parse_repo([])
    ensure_started(repo, [])

    app_name = Mix.Project.config[:app] |> Atom.to_string |> Macro.camelize
    model_name = List.first(args) |> Macro.camelize

    IO.puts repo.aggregate(Module.concat(app_name, model_name), :count, :id)
  end
end

Then you can get the row count of LineItem model:

mix db.count line_item

Note that the Mix task above assumes that the application has single repository (data store).