Class: PGTrunk::Operations::MaterializedViews::Column

Inherits:
Object
  • Object
show all
Includes:
ActiveModel::Attributes, ActiveModel::Model, ActiveModel::Validations
Defined in:
lib/pg_trunk/operations/materialized_views/column.rb

Overview

Definition for the column change

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.build(data) ⇒ Object



11
12
13
# File 'lib/pg_trunk/operations/materialized_views/column.rb', line 11

def self.build(data)
  data.is_a?(self) ? data : new(**data)
end

Instance Method Details

#changesObject



36
37
38
# File 'lib/pg_trunk/operations/materialized_views/column.rb', line 36

def changes
  opts.except(:new_name)
end

#error_messagesObject



71
72
73
74
75
76
77
78
# File 'lib/pg_trunk/operations/materialized_views/column.rb', line 71

def error_messages
  validate
  errors&.messages&.flat_map do |k, v|
    v.map do |msg|
      "Column #{name.inspect}: #{k == :base ? msg : "#{k} #{msg}"}"
    end
  end
end

#invertObject



40
41
42
43
44
45
46
47
48
49
# File 'lib/pg_trunk/operations/materialized_views/column.rb', line 40

def invert
  return { name: new_name, new_name: name } if new_name.present?

  {
    name: name,
    storage: (from_storage || :UNDEFINED if storage.present?),
    statistics: (0 if statistics.present?),
    n_distinct: (0 if n_distinct.present?),
  }.compact
end

#optsObject



32
33
34
# File 'lib/pg_trunk/operations/materialized_views/column.rb', line 32

def opts
  to_h.except(:name)
end

#to_hObject

Hashify definitions



24
25
26
27
28
29
30
# File 'lib/pg_trunk/operations/materialized_views/column.rb', line 24

def to_h
  @to_h ||=
    attributes
    .symbolize_keys
    .transform_values(&:presence)
    .compact
end

#to_sql(_version = "10") ⇒ Array<String>

Build SQL snippets for the column definition

Returns:

  • (Array<String>)


82
83
84
85
86
87
88
89
90
91
92
# File 'lib/pg_trunk/operations/materialized_views/column.rb', line 82

def to_sql(_version = "10")
  return ["RENAME COLUMN #{name.inspect} TO #{new_name.inspect}"] if new_name

  alter = "ALTER COLUMN #{name.inspect}"
  [
    *("#{alter} SET STATISTICS #{statistics}" if statistics),
    *("#{alter} SET (n_distinct = #{n_distinct})" if n_distinct),
    *("#{alter} RESET (n_distinct)" if n_distinct&.zero?),
    *("#{alter} SET STORAGE #{storage.to_s.upcase}" if storage.present?),
  ]
end