Skip to content

Commit

Permalink
feat: remove_enum_value
Browse files Browse the repository at this point in the history
  • Loading branch information
hosembafer authored Jul 24, 2020
1 parent 4ce4bc1 commit e1bb5ca
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 0 deletions.
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 @@ -67,6 +67,15 @@ def add_enum_value(name, value, after: nil, before: nil, if_not_exists: 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 @@ -74,6 +74,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

0 comments on commit e1bb5ca

Please sign in to comment.