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
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,14 @@ To add a value into existing enum:
add_enum_value :mood, "pensive"
```

To remove a value from existing enum:

> :warning: Make sure that value is not used anywhere in the database.

```ruby
remove_enum_value :mood, "pensive"
```

To add a new enum column to an existing table:

```ruby
Expand Down
9 changes: 9 additions & 0 deletions lib/active_record/postgres_enum/postgresql_adapter.rb
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,15 @@ def add_enum_value(name, value, after: nil, before: nil)
execute sql
end

def remove_enum_value(name, value)
sql = %{
DELETE FROM pg_enum
WHERE enumlabel=#{quote value}
AND enumtypid=(SELECT oid FROM pg_type WHERE typname='#{name}')
}
execute sql
end

def rename_enum_value(name, existing_value, new_value)
raise "Renaming enum values is only supported in PostgreSQL 10.0+" unless rename_enum_value_supported?

Expand Down
29 changes: 29 additions & 0 deletions spec/active_record/postgres_enum_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,35 @@
expect(connection.enums[:foo]).to eq ["a1", "a2", 'a"3']
end

it "removes an enum value" do
expect { connection.remove_enum_value(:foo, "a1") }.to_not raise_error
expect(connection.enums[:foo]).to eq %w(a2)
end

it "removes an enum value with a space" do
expect { connection.add_enum_value(:foo, "a 3") }.to_not raise_error
expect { connection.remove_enum_value(:foo, "a 3") }.to_not raise_error
expect(connection.enums[:foo]).to eq %w(a1 a2)
end

it "removes an enum value with a comma" do
expect { connection.add_enum_value(:foo, "a,3") }.to_not raise_error
expect { connection.remove_enum_value(:foo, "a,3") }.to_not raise_error
expect(connection.enums[:foo]).to eq %w(a1 a2)
end

it "removes an enum value with a single quote" do
expect { connection.add_enum_value(:foo, "a'3") }.to_not raise_error
expect { connection.remove_enum_value(:foo, "a'3") }.to_not raise_error
expect(connection.enums[:foo]).to eq %w(a1 a2)
end

it "removes an enum value with a double quote" do
expect { connection.add_enum_value(:foo, "a\"3") }.to_not raise_error
expect { connection.remove_enum_value(:foo, "a\"3") }.to_not raise_error
expect(connection.enums[:foo]).to eq %w(a1 a2)
end

it "renames an enum value" do
expect { connection.rename_enum_value(:foo, "a2", "b2") }.to_not raise_error
expect(connection.enums[:foo]).to eq %w(a1 b2)
Expand Down