Skip to content

Commit 17dd4a5

Browse files
committed
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`.
1 parent 49b8e70 commit 17dd4a5

File tree

4 files changed

+15
-2
lines changed

4 files changed

+15
-2
lines changed

activerecord/CHANGELOG.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,8 @@
1+
* Add support for PostgreSQL `IF NOT EXISTS` via the `:if_not_exists` option
2+
on the `add_enum_value` method.
3+
4+
*Ariel Rzezak*
5+
16
* When running `db:migrate` on a fresh database, load the database schema before running migrations.
27

38
*Andrew Novoselac*

activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -584,7 +584,9 @@ def rename_enum(name, options = {})
584584
# Add enum value to an existing enum type.
585585
def add_enum_value(type_name, value, options = {})
586586
before, after = options.values_at(:before, :after)
587-
sql = +"ALTER TYPE #{quote_table_name(type_name)} ADD VALUE '#{value}'"
587+
sql = +"ALTER TYPE #{quote_table_name(type_name)} ADD VALUE"
588+
sql << " IF NOT EXISTS" if options[:if_not_exists]
589+
sql << " '#{value}'"
588590

589591
if before && after
590592
raise ArgumentError, "Cannot have both :before and :after at the same time"

activerecord/test/cases/adapters/postgresql/enum_test.rb

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -128,9 +128,14 @@ def test_schema_dump_added_enum_value
128128
@connection.add_enum_value :mood, :nervous, after: :ok
129129
@connection.add_enum_value :mood, :glad
130130

131+
assert_nothing_raised do
132+
@connection.add_enum_value :mood, :glad, if_not_exists: true
133+
@connection.add_enum_value :mood, :curious, if_not_exists: true
134+
end
135+
131136
output = dump_table_schema("postgresql_enums")
132137

133-
assert_includes output, 'create_enum "mood", ["sad", "angry", "ok", "nervous", "happy", "glad"]'
138+
assert_includes output, 'create_enum "mood", ["sad", "angry", "ok", "nervous", "happy", "glad", "curious"]'
134139
end
135140

136141
def test_schema_dump_renamed_enum_value

guides/source/active_record_postgresql.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -332,6 +332,7 @@ def up
332332
add_enum_value :article_state, "archived" # will be at the end after published
333333
add_enum_value :article_state, "in review", before: "published"
334334
add_enum_value :article_state, "approved", after: "in review"
335+
add_enum_value :article_state, "rejected", if_not_exists: true # won't raise an error if the value already exists
335336
end
336337
```
337338

0 commit comments

Comments
 (0)