Module: Mimi::DB::Dictate::SchemaDiff

Defined in:
lib/mimi/db/dictate/schema_diff.rb

Constant Summary collapse

DEFAULT_OPTIONS =
{
}.freeze

Class Method Summary collapse

Class Method Details

.diff(from, to, opts = {}) ⇒ Hash

Compares two schema definitions

Returns:

  • (Hash)

    :columns, :indexes => :from, :to



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/mimi/db/dictate/schema_diff.rb', line 15

def self.diff(from, to, opts = {})
  _options = DEFAULT_OPTIONS.merge(opts)
  result = { table_name: from.table_name, columns: {}, indexes: {} }
  all_column_names = (from.columns.values.map(&:name) + to.columns.values.map(&:name)).uniq
  all_column_names.each do |c|
    if from.columns[c] && to.columns[c].nil?
      result[:columns][c] = { from: from.columns[c], to: nil }
    elsif from.columns[c] && to.columns[c] && !(from.columns[c] == to.columns[c])
      result[:columns][c] = { from: from.columns[c], to: to.columns[c] }
    elsif from.columns[c].nil? && to.columns[c]
      result[:columns][c] = { from: nil, to: to.columns[c] }
    end
  end
  from_indexes = from.indexes.map { |i| [i.columns, i] }.to_h
  to_indexes   = to.indexes.map { |i| [i.columns, i] }.to_h
  all_index_cols = (from_indexes.keys + to_indexes.keys).uniq
  all_index_cols.each do |cc|
    if from_indexes[cc] && to_indexes[cc].nil?
      result[:indexes][cc] = { from: from_indexes[cc], to: nil }
    elsif from_indexes[cc] && to_indexes[cc]
      # index diff is not supported
    elsif from_indexes[cc].nil? && to_indexes[cc]
      result[:indexes][cc] = { from: nil, to: to_indexes[cc]}
    end
  end

  result
end