Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions lib/active_record/postgres_enum/postgresql_adapter.rb
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,10 @@ def rename_enum(name, new_name)
execute "ALTER TYPE #{name} RENAME TO #{new_name}"
end

def add_enum_value(name, value, after: nil, before: nil)
sql = "ALTER TYPE #{name} ADD VALUE #{quote value}"
def add_enum_value(name, value, after: nil, before: nil, if_not_exists: nil)
if_not_exists_statement = 'IF NOT EXISTS' if if_not_exists

sql = "ALTER TYPE #{name} ADD VALUE #{if_not_exists_statement} #{quote value}"
if after
sql += " AFTER #{quote after}"
elsif before
Expand Down
9 changes: 9 additions & 0 deletions spec/active_record/postgres_enum_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,15 @@
expect(connection.enums[:foo]).to eq %w(a1 a2 a3)
end

it "adds an enum value if not exists" do
expect { connection.add_enum_value(:foo, "a1", if_not_exists: true) }.to_not raise_error
end

it "fails to add an enum value if exists" do
expect { connection.add_enum_value(:foo, "a1", if_not_exists: false) }.to raise_error
expect { connection.add_enum_value(:foo, "a2") }.to raise_error
end

it "adds an enum value after a given value" do
expect { connection.add_enum_value(:foo, "a3", after: "a1") }.to_not raise_error
expect(connection.enums[:foo]).to eq %w(a1 a3 a2)
Expand Down