reltask.ex (2496B)
1 # Zenflows is designed to implement the Valueflows vocabulary, 2 # written and maintained by srfsh <info@dyne.org>. 3 # Copyright (C) 2021-2023 Dyne.org foundation <foundation@dyne.org>. 4 # 5 # This program is free software: you can redistribute it and/or modify 6 # it under the terms of the GNU Affero General Public License as published by 7 # the Free Software Foundation, either version 3 of the License, or 8 # (at your option) any later version. 9 # 10 # This program is distributed in the hope that it will be useful, 11 # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 # GNU Affero General Public License for more details. 14 # 15 # You should have received a copy of the GNU Affero General Public License 16 # along with this program. If not, see <https://www.gnu.org/licenses/>. 17 18 defmodule Zenflows.Reltask do 19 @moduledoc "Relesea task commands, such as migrate, rollback." 20 21 @typep repo() :: Ecto.Repo.t() 22 23 @doc "Apply migrations." 24 @spec migrate() :: :ok 25 def migrate() do 26 :ok = mig_run(:up, all: true) 27 end 28 29 @spec migrate(Keyword.t()) :: :ok 30 def migrate(opts) when is_list(opts) do 31 :ok = mig_run(:up, opts) 32 end 33 34 @spec migrate(repo()) :: :ok 35 def migrate(repo) do 36 :ok = mig_run(repo, :up, all: true) 37 end 38 39 @doc "Apply migrations." 40 @spec migrate(repo(), Keyword.t()) :: :ok 41 def migrate(repo, opts) do 42 :ok = mig_run(repo, :up, opts) 43 end 44 45 @doc "Rollback to migrations." 46 @spec rollback(Keyword.t()) :: :ok 47 def rollback(opts) when is_list(opts) do 48 :ok = mig_run(:down, opts) 49 end 50 51 @spec rollback(integer()) :: :ok 52 def rollback(ver) do 53 :ok = mig_run(:down, to: ver) 54 end 55 56 @doc "Rollback to migrations." 57 @spec rollback(repo(), Keyword.t()) :: :ok 58 def rollback(repo, opts) when is_list(opts) do 59 :ok = mig_run(repo, :down, opts) 60 end 61 62 @spec rollback(repo(), integer()) :: :ok 63 def rollback(repo, ver) do 64 :ok = mig_run(repo, :down, to: ver) 65 end 66 67 # Run migrations of all repos. See `mig_run/3` for more info. 68 @spec mig_run(:up | :down, Keyword.t()) :: :ok 69 defp mig_run(dir, opts) do 70 for repo <- repos() do 71 :ok = mig_run(repo, dir, opts) 72 end 73 74 :ok 75 end 76 77 # Run migrations of a given repo. See `Ecto.Migrator.run/4` for more 78 # info. 79 @spec mig_run(repo(), :up | :down, Keyword.t()) :: :ok 80 defp mig_run(repo, dir, opts) do 81 alias Ecto.Migrator, as: M 82 83 {:ok, _, _} = M.with_repo(repo, &M.run(&1, dir, opts)) 84 85 :ok 86 end 87 88 @spec repos() :: [repo()] 89 defp repos() do 90 Application.load(:zenflows) 91 Application.fetch_env!(:zenflows, :ecto_repos) 92 end 93 end