Class: PGTrunk::Operations::Enums::ChangeEnum

Inherits:
Base show all
Defined in:
lib/pg_trunk/operations/enums/change_enum.rb

Instance Method Summary collapse

Methods inherited from Base

#value

Methods included from PGTrunk::Operation::SQLHelpers

#quote

Methods included from PGTrunk::Operation::RubyHelpers

#dump, #to_a, #to_opts, #to_ruby

Methods included from PGTrunk::Operation::Inversion

#invert!, #irreversible!

Methods included from PGTrunk::Operation::Validations

#error_messages

Methods included from PGTrunk::Operation::Attributes

#attributes, #initialize

Instance Method Details

#add_value(name, after: nil, before: nil) ⇒ Object

Add new value (irreversible!) If neither option is specified, the value will be added to the very end of the array. Notice, that all add-ons are made BEFORE renames.



48
49
50
# File 'lib/pg_trunk/operations/enums/change_enum.rb', line 48

def add_value(name, after: nil, before: nil)
  changes << Change.new(name: name, after: after, before: before)
end

#invertObject



73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/pg_trunk/operations/enums/change_enum.rb', line 73

def invert
  values_added = changes.any?(&:add?)
  raise IrreversibleMigration.new(self, nil, <<~MSG.squish) if values_added
    Removal of values from enumerated type is not supported by PostgreSQL,
    that's why adding new values can't be reverted.
  MSG

  undefined = inversion.select { |_, v| v.nil? }.keys.join(", ").presence
  raise IrreversibleMigration.new(self, nil, <<~MSG.squish) if undefined
    Undefined values to revert #{undefined}.
  MSG

  self.class.new(**to_h, **inversion)
end

#rename_value(name, to: nil) ⇒ Object

Rename the value to new unique name (reversible)



53
54
55
# File 'lib/pg_trunk/operations/enums/change_enum.rb', line 53

def rename_value(name, to: nil)
  changes << Change.new(name: name, new_name: to)
end

#to_hObject



88
89
90
# File 'lib/pg_trunk/operations/enums/change_enum.rb', line 88

def to_h
  super.tap { |data| data[:changes]&.map!(&:to_h) }
end

#to_sql(version) ⇒ Object



64
65
66
67
68
69
70
71
# File 'lib/pg_trunk/operations/enums/change_enum.rb', line 64

def to_sql(version)
  raise <<~MSG.squish if version < "12" && changes.any?(&:add?)
    Adding new values to enumerable types inside a migration
    is supported in PostgreSQL v12+.
  MSG

  [*add_values, *rename_values, *change_comment].join(" ")
end