4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

カスタムMixタスクでEcto経由でデータベースを操作する(Elixir)

Last updated at Posted at 2020-11-07

はじめに

  • カスタムMixタスクでEcto経由でデータベースを操作したいです
    • Mix.Taskは独自に作れるんです
  • 私は前提知識として、lib/mix/tasks/hoge.exつくれば、mix hogeで実行できるタスクを実装できるのですよね〜 というところまでは知っていました
  • 今回はそのタスクの中でEcto経由でデータベースを操作することをしてみたときに、エラーに遭遇しまして、解決策がわかりましたのでその記録を残しておきます
    • Phoenixタグをつけるかどうかは迷ったのですが、まあPhoenixアプリを作っているときに遭遇したのでつけておきました

カスタムMixタスク

lib/mix/tasks/db_all_delete.ex
defmodule Mix.Tasks.DbAllDelete do
  use Mix.Task

  def run(_) do
    Mix.Task.run "app.start", []

    Demo.Repo.delete_all(Demo.Accounts.User)
  end
end
  • Mix.Task.run "app.start", []の呼び出しが必要になります
  • Gigalixirにデプロイしている場合には、gigalixir run mix db_all_deleteなんて感じで実行できます

Mix.Task.run "app.start", []の呼び出しがない場合

$ mix db_all_delete                                                                                                                     
Compiling 1 file (.ex)
** (RuntimeError) could not lookup Ecto repo Demo.Repo because it was not started or it does not exist
    lib/ecto/repo/registry.ex:19: Ecto.Repo.Registry.lookup/1
    lib/ecto/repo/queryable.ex:210: Ecto.Repo.Queryable.execute/4
    lib/mix/tasks/db_all_delete.ex:7: Mix.Tasks.DbAllDelete.run/1
    (mix 1.10.4) lib/mix/task.ex:330: Mix.Task.run_task/3
    (mix 1.10.4) lib/mix/cli.ex:82: Mix.CLI.run_task/2
    (elixir 1.10.4) lib/code.ex:926: Code.require_file/2

  • Ecto repoが始まっていないだなんだ言われています

参考記事

Wrapping Up :lgtm: :qiitan: :lgtm:

4
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?