Class: Mysqlknife::Swap

Inherits:
Object
  • Object
show all
Defined in:
lib/mysqlknife/swap.rb

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Swap

Returns a new instance of Swap.



5
6
7
8
9
10
11
12
13
# File 'lib/mysqlknife/swap.rb', line 5

def initialize(options = {})
  databases  = options[:databases].split(',')
  @db_from   = databases[0]
  @db_to     = databases[1]
  @conn_from = Connection.new(options, @db_from)
  @conn_to   = Connection.new(options, @db_to)
  @from      = Sql.new(@db_from)
  @to        = Sql.new(@db_to)
end

Instance Method Details

#allObject



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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/mysqlknife/swap.rb', line 15

def all
  sql = []

  # Swap tables.
  tables_from = @conn_from.execute(@from.tables)
  tables_from = tables_from.map { |f| f['name'] } if tables_from
  tables_to   = @conn_to.execute(@to.tables)
  tables_to   = tables_to.map { |t| t['name'] } if tables_to
  views_from  = @conn_from.execute(@from.views)
  views_to    = @conn_to.execute(@to.views)

  if tables_from && tables_to
    swap      = tables_from & tables_to
    rename    = (tables_from - tables_to) + (tables_to - tables_from)

    unless swap.empty?
      swap.map do | table |
        sql << @to.swap_table(@db_from, table)
      end
    end

    unless rename.empty?
      rename.map do | table |
        if tables_from.include?(table)
          sql << @from.rename_table(@db_to, table)
        else
          sql << @to.rename_table(@db_from, table)
        end
      end
    end
  end

  # Drop views and create new views in another DB.
  sql << @from.use
  views_from.each do | view |
    sql << @from.drop_view(view['name'])
  end
  views_to.each do | view |
    sql << @from.create_view(view['name'], view['code'])
  end

  sql << @to.use
  views_to.each do | view |
    sql << @to.drop_view(view['name'])
  end
  views_from.each do | view |
    sql << @to.create_view(view['name'], view['code'])
  end

  sql
end