Class: DbVcs::Adapters::Mysql

Inherits:
Object
  • Object
show all
Extended by:
DbVcs::AdapterInterface
Defined in:
lib/db_vcs/adapters/mysql.rb

Defined Under Namespace

Classes: Config

Class Method Summary collapse

Methods included from DbVcs::AdapterInterface

config, connection, copy_database, create_database, db_exists?, drop_by_dbname, list_databases

Class Method Details

.configDbVcs::Adapters::Mysql::Config



29
30
31
# File 'lib/db_vcs/adapters/mysql.rb', line 29

def config
  DbVcs.config.mysql_config
end

.connectionMysql2::Client

Returns:

  • (Mysql2::Client)


34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/db_vcs/adapters/mysql.rb', line 34

def connection
  @connection ||=
    begin
      require "mysql2"
      Mysql2::Client.new(
        host: config.host,
        username: config.username,
        port: config.port,
        password: config.password
      )
    end
end

.copy_database(to_db, from_db) ⇒ Object

Returns void.

Parameters:

  • to_db (String)
  • from_db (String)

Returns:

  • void



58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/db_vcs/adapters/mysql.rb', line 58

def copy_database(to_db, from_db)
  create_opts =
    connection.query(<<~SQL).first
      SELECT `DEFAULT_CHARACTER_SET_NAME` as charset, `DEFAULT_COLLATION_NAME` as collation
      FROM `INFORMATION_SCHEMA`.`SCHEMATA` WHERE `SCHEMA_NAME` = '#{from_db}' LIMIT 1
    SQL
  connection.query(<<~SQL)
    CREATE DATABASE #{to_db} CHARACTER SET #{create_opts["charset"]} COLLATE #{create_opts["collation"]}
  SQL
  password_opt = config.password.to_s.strip.empty? ? "" : "-p#{config.password}"
  command =
    <<~SH
    #{config.mysqldump_path} -u #{config.username} #{password_opt} -h #{config.host} -P #{config.port} #{from_db} \
    | #{config.mysql_path} -u #{config.username} #{password_opt} -h #{config.host} -P #{config.port} #{to_db}
  SH
  `#{command}`
end

.create_database(db_name) ⇒ Object

Returns void.

Parameters:

  • db_name (String)

Returns:

  • void



78
79
80
# File 'lib/db_vcs/adapters/mysql.rb', line 78

def create_database(db_name)
  connection.query("CREATE DATABASE #{db_name}")
end

.db_exists?(db_name) ⇒ Boolean

Parameters:

  • db_name (String)

Returns:

  • (Boolean)


49
50
51
52
53
# File 'lib/db_vcs/adapters/mysql.rb', line 49

def db_exists?(db_name)
  !connection
     .query("SELECT 1 as one FROM `INFORMATION_SCHEMA`.`SCHEMATA` WHERE `SCHEMA_NAME` = '#{db_name}' LIMIT 1")
     .first.nil?
end

.drop_by_dbname(db_name) ⇒ void

This method returns an undefined value.

Parameters:

  • db_name (String)


89
90
91
# File 'lib/db_vcs/adapters/mysql.rb', line 89

def drop_by_dbname(db_name)
  connection.query("DROP DATABASE #{db_name}")
end

.list_databasesArray<String>

Returns:

  • (Array<String>)


83
84
85
# File 'lib/db_vcs/adapters/mysql.rb', line 83

def list_databases
  connection.query("SELECT `SCHEMA_NAME` FROM `INFORMATION_SCHEMA`.`SCHEMATA`").to_a.flat_map(&:values)
end