Created
September 30, 2022 16:42
-
-
Save moroz/2ac25d60801f04ca2a89963ea39249b8 to your computer and use it in GitHub Desktop.
Automatically migrate Ecto repo 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 Gg.Application do | |
# See https://hexdocs.pm/elixir/Application.html | |
# for more information on OTP Applications | |
@moduledoc false | |
@migrator if Mix.env() in [:prod, :staging], do: [MyApp.Migrator], else: [] | |
use Application | |
@impl true | |
def start(_type, _args) do | |
children = | |
[ | |
# Start the Ecto repository | |
Gg.Repo, | |
# Start the Telemetry supervisor | |
GgWeb.Telemetry, | |
# Start the PubSub system | |
{Phoenix.PubSub, name: Gg.PubSub}, | |
# Start the Endpoint (http/https) | |
GgWeb.Endpoint | |
] ++ @migrator | |
# See https://hexdocs.pm/elixir/Supervisor.html | |
# for other strategies and supported options | |
opts = [strategy: :one_for_one, name: Gg.Supervisor] | |
Supervisor.start_link(children, opts) | |
end | |
# Tell Phoenix to update the endpoint configuration | |
# whenever the application is updated. | |
@impl true | |
def config_change(changed, _new, removed) do | |
GgWeb.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