Created
April 3, 2021 05:30
-
-
Save moroz/654e44770d646c715fc89c2600751e40 to your computer and use it in GitHub Desktop.
Automatically migrate Ecto database in release
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule MyApp.Application do | |
# See https://hexdocs.pm/elixir/Application.html | |
# for more information on OTP Applications | |
@moduledoc false | |
use Application | |
@migrator if Mix.env() in [:prod, :staging], do: [MyApp.Migrator], else: [] | |
def start(_type, _args) do | |
children = | |
[ | |
MyApp.Repo, | |
MyAppWeb.Telemetry, | |
{Phoenix.PubSub, name: MyApp.PubSub}, | |
MyAppWeb.Endpoint | |
] ++ @migrator | |
# See https://hexdocs.pm/elixir/Supervisor.html | |
# for other strategies and supported options | |
opts = [strategy: :one_for_one, name: MyApp.Supervisor] | |
Supervisor.start_link(children, opts) | |
end | |
# Tell Phoenix to update the endpoint configuration | |
# whenever the application is updated. | |
def config_change(changed, _new, removed) do | |
MyAppWeb.Endpoint.config_change(changed, removed) | |
:ok | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule MyApp.Migrator do | |
@moduledoc """ | |
Run Ecto migrations upon application startup. | |
Used to automatically trigger database migrations in a CD setup. | |
""" | |
@otp_app :my_app | |
@repo MyApp.Repo | |
require Logger | |
use Task, restart: :transient | |
def start_link(arg), do: Task.start_link(__MODULE__, :run, [arg]) | |
def run(_) do | |
Logger.info("#{inspect(__MODULE__)} is running database migrations") | |
migrations_dir = :code.priv_dir(@otp_app) |> Path.join("repo/migrations") | |
Ecto.Migrator.run(@repo, migrations_dir, :up, all: true) | |
Logger.info("#{inspect(__MODULE__)} has finished running migrations") | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment