Module: ActiveRecord::PGEnum::SchemaStatements

Defined in:
lib/active_record/pg_enum/schema_statements.rb

Instance Method Summary collapse

Instance Method Details

#add_enum_value(type, value, options = {}) ⇒ Object

Add a new value to an existing ENUM type. Only one value at a time is supported by PostgreSQL.

Options:

before: add value BEFORE the given value
after:  add value AFTER the given value

Example:

add_enum_value("foo_type", "quux", before: "bar")


34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/active_record/pg_enum/schema_statements.rb', line 34

def add_enum_value(type, value, options = {})
  before, after = options.values_at(:before, :after)
  cmd = "ALTER TYPE #{type} ADD VALUE '#{value}'"

  if before && after
    raise ArgumentError, "Cannot have both :before and :after at the same time"
  elsif before
    cmd << " BEFORE '#{before}'"
  elsif after
    cmd << " AFTER '#{after}'"
  end

  execute(cmd).tap { reload_type_map }
end

#drop_enum(name, values_for_revert = nil) ⇒ Object

Drop an ENUM type from the database.



10
11
12
13
14
# File 'lib/active_record/pg_enum/schema_statements.rb', line 10

def drop_enum(name, values_for_revert = nil)
  execute("DROP TYPE #{name}").tap {
    reload_type_map
  }
end

#rename_enum(name, options = {}) ⇒ Object

Rename an existing ENUM type



17
18
19
20
21
22
# File 'lib/active_record/pg_enum/schema_statements.rb', line 17

def rename_enum(name, options = {})
  to = options.fetch(:to) { raise ArgumentError, ":to is required" }
  execute("ALTER TYPE #{name} RENAME TO #{to}").tap {
    reload_type_map
  }
end

#rename_enum_value(type, options = {}) ⇒ Object

Change the label of an existing ENUM value

Options:

from: The original label string
to:   The desired label string

Example:

rename_enum_value "foo_type", from: "quux", to: "Quux"

Note: This feature requires PostgreSQL 10 or later



60
61
62
63
64
65
66
67
# File 'lib/active_record/pg_enum/schema_statements.rb', line 60

def rename_enum_value(type, options = {})
  from = options.fetch(:from) { raise ArgumentError, ":from is required" }
  to   = options.fetch(:to)   { raise ArgumentError, ":to is required" }

  execute("ALTER TYPE #{type} RENAME VALUE '#{from}' TO '#{to}'").tap {
    reload_type_map
  }
end