How do you truncate a table in ecto?

Couldn’t find anything, but maybe

Repo.query("TRUNCATE my_table", [])

would work?

You can probably define such a function for development and testing environments in your Repo module

defmodule MyApp.Repo do
  use Ecto.Repo, otp_app: :my_app

  if Mix.env() in [:dev, :test] do
    @spec truncate(Ecto.Schema.t()) :: :ok
    def truncate(schema) do
      table_name = schema.__schema__(:source)
      query("TRUNCATE #{table_name}", [])
      :ok
    end
  end
end

and then call it as

MyApp.Repo.truncate(MyApp.User)
2 Likes