Add if_not_exists option to add_enum_value

Adds support to use the PostgreSQL option `IF NOT EXISTS` when adding
enum values via `add_enum_value`.
This commit is contained in:
Ariel Rzezak 2024-09-13 16:16:45 -03:00
parent 49b8e70760
commit 17dd4a501e
4 changed files with 15 additions and 2 deletions

View File

@ -1,3 +1,8 @@
* Add support for PostgreSQL `IF NOT EXISTS` via the `:if_not_exists` option
on the `add_enum_value` method.
*Ariel Rzezak*
* When running `db:migrate` on a fresh database, load the database schema before running migrations.
*Andrew Novoselac*

View File

@ -584,7 +584,9 @@ module ActiveRecord
# Add enum value to an existing enum type.
def add_enum_value(type_name, value, options = {})
before, after = options.values_at(:before, :after)
sql = +"ALTER TYPE #{quote_table_name(type_name)} ADD VALUE '#{value}'"
sql = +"ALTER TYPE #{quote_table_name(type_name)} ADD VALUE"
sql << " IF NOT EXISTS" if options[:if_not_exists]
sql << " '#{value}'"
if before && after
raise ArgumentError, "Cannot have both :before and :after at the same time"

View File

@ -128,9 +128,14 @@ class PostgresqlEnumTest < ActiveRecord::PostgreSQLTestCase
@connection.add_enum_value :mood, :nervous, after: :ok
@connection.add_enum_value :mood, :glad
assert_nothing_raised do
@connection.add_enum_value :mood, :glad, if_not_exists: true
@connection.add_enum_value :mood, :curious, if_not_exists: true
end
output = dump_table_schema("postgresql_enums")
assert_includes output, 'create_enum "mood", ["sad", "angry", "ok", "nervous", "happy", "glad"]'
assert_includes output, 'create_enum "mood", ["sad", "angry", "ok", "nervous", "happy", "glad", "curious"]'
end
def test_schema_dump_renamed_enum_value

View File

@ -332,6 +332,7 @@ def up
add_enum_value :article_state, "archived" # will be at the end after published
add_enum_value :article_state, "in review", before: "published"
add_enum_value :article_state, "approved", after: "in review"
add_enum_value :article_state, "rejected", if_not_exists: true # won't raise an error if the value already exists
end
```