Skip to content

Commit

Permalink
add if_not_exists option to add_value_to_type (#13)
Browse files Browse the repository at this point in the history
  • Loading branch information
wmorris92 committed Jan 10, 2024
1 parent 4ab7192 commit 7c4c56a
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 1 deletion.
17 changes: 16 additions & 1 deletion lib/ecto_enum_migration.ex
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ defmodule EctoEnumMigration do
def up do
add_value_to_type(:status, :finished)
end
def down do
end
end
Expand All @@ -168,6 +168,12 @@ defmodule EctoEnumMigration do
add_value_to_type(:status, :finished, after: :started)
```
Can specify to only add value if not exists with the `:if_not_exists` option
```elixir
add_value_to_type(:status, :finished, if_not_exists: true)
```
"""
@spec add_value_to_type(name :: atom(), value :: atom(), opts :: Keyword.t()) ::
:ok | no_return()
Expand All @@ -177,6 +183,7 @@ defmodule EctoEnumMigration do
"ALTER TYPE",
type_name(name, opts),
"ADD VALUE",
if_not_exists_sql(opts),
to_value(value),
before_after(opts),
";"
Expand Down Expand Up @@ -267,6 +274,14 @@ defmodule EctoEnumMigration do
end
end

defp if_not_exists_sql(opts) do
if Keyword.get(opts, :if_not_exists, false) do
"IF NOT EXISTS"
else
[]
end
end

defp execute_query(terms) do
terms
|> Enum.reject(&(is_nil(&1) || &1 == []))
Expand Down
28 changes: 28 additions & 0 deletions test/ecto_enum_migration_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,16 @@ defmodule EctoEnumMigrationTest do
end
end

defmodule AddValueToTypeIfNotExistsMigration do
use Ecto.Migration
import EctoEnumMigration
@disable_ddl_transaction true

def change do
add_value_to_type(:status, :finished, if_not_exists: true)
end
end

defmodule AddValueToTypeWithCustomSchemaMigration do
use Ecto.Migration
import EctoEnumMigration
Expand Down Expand Up @@ -296,6 +306,24 @@ defmodule EctoEnumMigrationTest do
end
end

test "supports if not exists option" do
create_version = version_number()
add_value_version = version_number()
add_value_version_again = version_number()

:ok = up(create_version, CreateTypeMigration)
:ok = up(add_value_version, AddValueToTypeIfNotExistsMigration)
:ok = up(add_value_version_again, AddValueToTypeIfNotExistsMigration)

assert current_types() == %{
"public.status" => ["registered", "active", "inactive", "archived", "finished"]
}

assert_raise Ecto.MigrationError, ~r/cannot reverse migration command/, fn ->
:ok = down(add_value_version, AddValueToTypeIfNotExistsMigration)
end
end

test "supports before option" do
create_version = version_number()
add_value_version = version_number()
Expand Down

0 comments on commit 7c4c56a

Please sign in to comment.