diff --git a/lib/active_record/postgres_enum/postgresql_adapter.rb b/lib/active_record/postgres_enum/postgresql_adapter.rb index 58dc3d1..d9634a3 100644 --- a/lib/active_record/postgres_enum/postgresql_adapter.rb +++ b/lib/active_record/postgres_enum/postgresql_adapter.rb @@ -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 diff --git a/spec/active_record/postgres_enum_spec.rb b/spec/active_record/postgres_enum_spec.rb index 055933b..363b296 100644 --- a/spec/active_record/postgres_enum_spec.rb +++ b/spec/active_record/postgres_enum_spec.rb @@ -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)