Skip to content

Commit

Permalink
Allow --repo option for phx.gen.schema
Browse files Browse the repository at this point in the history
  • Loading branch information
MikaAK authored and Gazler committed Oct 4, 2023
1 parent e6d0678 commit ce07beb
Showing 1 changed file with 31 additions and 3 deletions.
34 changes: 31 additions & 3 deletions lib/mix/tasks/phx.gen.schema.ex
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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))
Expand All @@ -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},
]
Expand Down

0 comments on commit ce07beb

Please sign in to comment.