Skip to content

Instantly share code, notes, and snippets.

@sgyyz
Created March 18, 2019 03:23
Show Gist options
  • Save sgyyz/f6bc191c2e8ce1b3621bfb6df84f73e3 to your computer and use it in GitHub Desktop.
Save sgyyz/f6bc191c2e8ce1b3621bfb6df84f73e3 to your computer and use it in GitHub Desktop.
defmodule Release.Tasks do
@start_apps [
:postgrex,
:ecto,
:ecto_sql
]
@app_mods [
DockerizeElixir
]
########## create db base if it dose not exist ############
def create_db do
Enum.each(@app_mods, &create_db_for/1)
:init.stop()
end
defp create_db_for(mod) do
IO.puts("Create DB for #{inspect(mod)}")
## get application
app = Application.get_application(mod)
## get all ecto repos for this application
repos = Application.get_env(app, :ecto_repos, [])
Enum.each(repos, &ensure_repo_created/1)
end
defp ensure_repo_created(repo) do
case repo.__adapter__.storage_up(repo.config) do
:ok ->
IO.puts("create database success")
:ok
{:error, :already_up} ->
IO.puts("database is already up, ignore it")
:ok
{:error, term} ->
IO.puts("#{inspect(term)}")
{:error, term}
end
end
########## do the migration like: create table, run seeds ############
def migrate do
Enum.each(@app_mods, &migrate_for/1)
:init.stop()
end
defp migrate_for(mod) do
## get application
app = Application.get_application(mod)
IO.puts("Starting dependencies")
# Start apps necessary for executing migrations
Enum.each(@start_apps, &Application.ensure_all_started/1)
# Start the Repo(s) for myapp
IO.puts("Starting repos")
repos = Application.get_env(app, :ecto_repos, [])
Enum.each(repos, & &1.start_link(pool_size: 2))
# Run migrations
Enum.each(repos, &run_migrations_for/1)
# Run seed
Enum.each(repos, &run_seeds_for/1)
end
## Migration for single repo
defp run_migrations_for(repo) do
app = Keyword.get(repo.config, :otp_app)
IO.puts("Running migrations for #{app}")
Ecto.Migrator.run(repo, migrations_path(repo), :up, all: true)
end
## Run seed for single repo
defp run_seeds_for(repo) do
# Run the seed script if it exists
seed_script = seeds_path(repo)
if File.exists?(seed_script) do
IO.puts("Running seed script..")
Code.eval_file(seed_script)
end
end
defp migrations_path(repo), do: priv_path_for(repo, "migrations")
defp seeds_path(repo), do: priv_path_for(repo, "seeds.exs")
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