Last active
March 31, 2024 15:53
-
-
Save Chervychnyk/b6f561d5d4df4704ac3dd0fdc77b58fc to your computer and use it in GitHub Desktop.
Example of migration and seed tasks for phoenix 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 YourApp.ReleaseTasks do | |
@app :your_app | |
@repos Application.get_env(:your_app, :ecto_repos, []) | |
def migrate() do | |
Application.load(@app) | |
for repo <- @repos do | |
{:ok, _, _} = Ecto.Migrator.with_repo(repo, &Ecto.Migrator.run(&1, :up, all: true)) | |
end | |
end | |
def seed() do | |
Application.load(@app) | |
for repo <- @repos do | |
{:ok, _, _} = | |
Ecto.Migrator.with_repo(repo, fn repo -> | |
Ecto.Migrator.run(repo, :up, all: true) | |
run_seeds_for(repo) | |
end) | |
end | |
end | |
def rollback(repo, version) do | |
Application.load(@app) | |
{:ok, _, _} = Ecto.Migrator.with_repo(repo, &Ecto.Migrator.run(&1, :down, to: version)) | |
end | |
def run_mix_task() do | |
Application.load(@app) | |
IO.puts("Mix task started") | |
Mix.Tasks.Example.run(nil) | |
IO.puts("FIN") | |
end | |
defp run_seeds_for(repo) do | |
# Run the seed script if it exists | |
seed_script = priv_path_for(repo, "seeds.exs") | |
if File.exists?(seed_script) do | |
IO.puts("Running seed script..") | |
Code.eval_file(seed_script) | |
end | |
end | |
defp priv_path_for(repo, filename) do | |
app = Keyword.get(repo.config(), :otp_app) | |
repo_underscore = | |
repo | |
|> Module.split() | |
|> List.last() | |
|> Macro.underscore() | |
priv_dir = "#{:code.priv_dir(app)}" | |
Path.join([priv_dir, repo_underscore, filename]) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment