diff --git a/README.md b/README.md index 6d807b6..54831a7 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/lib/active_record/postgres_enum/postgresql_adapter.rb b/lib/active_record/postgres_enum/postgresql_adapter.rb index 58dc3d1..f8bc4a7 100644 --- a/lib/active_record/postgres_enum/postgresql_adapter.rb +++ b/lib/active_record/postgres_enum/postgresql_adapter.rb @@ -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? diff --git a/spec/active_record/postgres_enum_spec.rb b/spec/active_record/postgres_enum_spec.rb index 055933b..ced2e67 100644 --- a/spec/active_record/postgres_enum_spec.rb +++ b/spec/active_record/postgres_enum_spec.rb @@ -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)