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
12 changes: 9 additions & 3 deletions lib/active_record/postgres_enum/postgresql_adapter.rb
Original file line number Diff line number Diff line change
Expand Up @@ -42,13 +42,19 @@ def enums
end
end

def create_enum(name, values)
def create_enum(name, values, if_not_exists: nil)
return if if_not_exists && enums.include?(name.to_sym)

values = values.map { |v| quote v }
execute "CREATE TYPE #{name} AS ENUM (#{values.join(', ')})"
end

def drop_enum(name)
execute "DROP TYPE #{name}"
def drop_enum(name, cascade: nil, if_exists: nil)
if_exists_statement = 'IF EXISTS' if if_exists
cascade_statement = 'CASCADE' if cascade

sql = "DROP TYPE #{if_exists_statement} #{name} #{cascade_statement}"
execute sql
end

def rename_enum(name, new_name)
Expand Down
37 changes: 35 additions & 2 deletions spec/active_record/postgres_enum_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,44 @@
expect(connection.enums[:foo]).to eq %w(a1 a2)
end

it "creates an enum if not exists" do
expect { connection.create_enum(:foo, %w(a1 a2), if_not_exists: true) }.not_to raise_error
end

it "fails create an existing enum" do
expect { connection.create_enum(:foo, %w(a1 a2)) }.to raise_error StandardError
end

it "drops an enum" do
expect { connection.drop_enum(:foo) }.to_not raise_error
expect(connection.enums[:foo]).to be_nil
end

it "drops an enum if exists" do
expect { connection.drop_enum(:some_unknown_type, if_exists: true) }.to_not raise_error
end

it "fails drop a non existing enum" do
expect { connection.drop_enum(:some_unknown_type) }.to raise_error StandardError
end

context 'drops an enum with cascade' do
before do
connection.create_table :test_tbl_for_cascade do |t|
t.enum :baz, enum_name: :foo
end
end

it "fails drop an enum with cascade" do
expect { connection.drop_enum(:foo) }.to raise_error StandardError
end

it "drops an enum with cascade" do
expect { connection.drop_enum(:foo, cascade: true) }.to_not raise_error
expect(connection.columns('test_tbl_for_cascade').map(&:name)).to_not include('baz')
end
end

it "renames an enum" do
expect { connection.rename_enum(:foo, :bar) }.to_not raise_error
expect(connection.enums[:bar]).to eq %w(a1 a2)
Expand All @@ -40,8 +73,8 @@
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
expect { connection.add_enum_value(:foo, "a1", if_not_exists: false) }.to raise_error StandardError
expect { connection.add_enum_value(:foo, "a2") }.to raise_error StandardError
end

it "adds an enum value after a given value" do
Expand Down