From ce07bebdbebe66d76f513f92f88b4298dcf0126a Mon Sep 17 00:00:00 2001 From: MikaAK Date: Fri, 29 Jul 2022 13:32:57 -0700 Subject: [PATCH] Allow --repo option for phx.gen.schema --- lib/mix/tasks/phx.gen.schema.ex | 34 ++++++++++++++++++++++++++++++--- 1 file changed, 31 insertions(+), 3 deletions(-) diff --git a/lib/mix/tasks/phx.gen.schema.ex b/lib/mix/tasks/phx.gen.schema.ex index c6f49051e9..93c76ba3af 100644 --- a/lib/mix/tasks/phx.gen.schema.ex +++ b/lib/mix/tasks/phx.gen.schema.ex @@ -86,6 +86,21 @@ defmodule Mix.Tasks.Phx.Gen.Schema do Generated migration can use `binary_id` for schema's primary key and its references with option `--binary-id`. + ## repo + + Generated migration can use `repo` to set the migration repository + folder with option `--repo`. + + $ mix phx.gen.schema Blog.Post posts --repo MyApp.Repo.Auth + + ## migration_dir + + Generated migrations can be added to a specific `migration-dir` which sets the + migration folder path + + $ mix phx.gen.schema Blog.Post posts --migration-dir /path/to/directory + + ## prefix By default migrations and schemas are generated without a prefix. @@ -131,7 +146,7 @@ defmodule Mix.Tasks.Phx.Gen.Schema do alias Mix.Phoenix.Schema @switches [migration: :boolean, binary_id: :boolean, table: :string, - web: :string, context_app: :string, prefix: :string] + web: :string, context_app: :string, prefix: :string, repo: :string, migration_dir: :string] @doc false def run(args) do @@ -163,13 +178,23 @@ defmodule Mix.Tasks.Phx.Gen.Schema do opts = parent_opts |> Keyword.merge(schema_opts) + |> Keyword.put(:migration_dir, schema_opts[:migration_dir]) |> put_context_app(schema_opts[:context_app]) + |> maybe_update_repo_module schema = Schema.new(schema_name, plural, attrs, opts) schema end + defp maybe_update_repo_module(opts) do + if is_nil(opts[:repo]) do + opts + else + Keyword.update!(opts, :repo, &Module.concat([&1])) + end + end + defp put_context_app(opts, nil), do: opts defp put_context_app(opts, string) do Keyword.put(opts, :context_app, String.to_atom(string)) @@ -181,12 +206,15 @@ defmodule Mix.Tasks.Phx.Gen.Schema do end @doc false - def copy_new_files(%Schema{context_app: ctx_app} = schema, paths, binding) do + def copy_new_files(%Schema{context_app: ctx_app, repo: repo, opts: opts} = schema, paths, binding) do files = files_to_be_generated(schema) Mix.Phoenix.copy_from(paths, "priv/templates/phx.gen.schema", binding, files) if schema.migration? do - migration_path = Mix.Phoenix.context_app_path(ctx_app, "priv/repo/migrations/#{timestamp()}_create_#{schema.table}.exs") + repo_name = repo |> Module.split |> List.last |> Macro.underscore + migration_dir = opts[:migration_dir] || Mix.Phoenix.context_app_path(ctx_app, "priv/#{repo_name}/migrations/") + migration_path = Path.join(migration_dir, "#{timestamp()}_create_#{schema.table}.exs") + Mix.Phoenix.copy_from paths, "priv/templates/phx.gen.schema", binding, [ {:eex, "migration.exs", migration_path}, ]