Class: Migrate::Storage::Mysql

Inherits:
DB
  • Object
show all
Defined in:
lib/migrate/storage/mysql.rb

Instance Attribute Summary

Attributes inherited from DB

#config

Instance Method Summary collapse

Methods inherited from DB

#current_version, #delete, #extract_version, #get_migration, #highest_version, #list_migrations, #log_down, #log_up, #lowest_version, #migrations_from, #migrations_range, #new_migration, #next_version, #prev_version, #print, #type, #version_exists?

Constructor Details

#initialize(*args) ⇒ Mysql

Returns a new instance of Mysql.



6
7
8
9
10
11
12
13
14
15
# File 'lib/migrate/storage/mysql.rb', line 6

def initialize(*args)
  super
  @conn = Mysql2::Client.new(
    :database => @config.database,
    :host => @config.host,
    :port => @config.port,
    :username => @config.user,
    :password => @config.password,
  )
end

Instance Method Details

#create_tablesObject



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
# File 'lib/migrate/storage/mysql.rb', line 17

def create_tables
  Log.info("Creating version table")
  self.exec_sql <<-eos
  CREATE TABLE #{@config.version_info}
  (
    version INT PRIMARY KEY NOT NULL AUTO_INCREMENT,
    description TEXT,
    created_date TIMESTAMP NOT NULL,
    last_up TIMESTAMP NULL,
    last_down TIMESTAMP NULL
  );
  eos

  self.exec_sql <<-eos
  CREATE TABLE #{@config.version_number} (
    version int(11) not null,
    PRIMARY KEY (version)
  );
  eos

  self.exec_sql <<-eos
  INSERT INTO #{@config.version_number} VALUES(0);
  eos
  Log.success("Version table created")
end

#exec_sql(sql) ⇒ Object



50
51
52
53
54
55
56
57
58
# File 'lib/migrate/storage/mysql.rb', line 50

def exec_sql(sql)
  results = []
  result = @tx.query sql
  return [] if result == nil

  result.each do |row|
    results << row
  end
end

#has_txObject



60
61
62
# File 'lib/migrate/storage/mysql.rb', line 60

def has_tx
  @tx != nil
end

#tables_exists?Boolean

Returns:

  • (Boolean)


43
44
45
46
47
48
# File 'lib/migrate/storage/mysql.rb', line 43

def tables_exists?
  vi = self.exec_sql("SHOW TABLES LIKE '#{@config.version_info}'")
  vn = self.exec_sql("SHOW TABLES LIKE '#{@config.version_number}'")

  vi.length > 0 && vn.length > 0
end

#txObject



64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/migrate/storage/mysql.rb', line 64

def tx
  if has_tx
    yield
  else
    begin
      @conn.query "BEGIN;"
      @tx = @conn
      yield
      @conn.query "COMMIT;"
    rescue Exception => e
      @conn.query "ROLLBACK;"
      raise e
    ensure
      @tx = nil
    end
  end
end