class SqlMigrate::Migrator

Constants

VERSION_TABLE_NAME

Attributes

config[RW]

Public Class Methods

new(config = nil) click to toggle source
# File lib/sql_migrate/migrator.rb, line 10
def initialize(config = nil)
  @config = config || Config.new
end

Public Instance Methods

applied_versions() click to toggle source
# File lib/sql_migrate/migrator.rb, line 46
def applied_versions
  connection.query("select * from #{VERSION_TABLE_NAME}", as: :array).to_a.flatten
end
create_migrate_versions_if_not_exist() click to toggle source
# File lib/sql_migrate/migrator.rb, line 29
    def create_migrate_versions_if_not_exist
      unless table_names.include?(VERSION_TABLE_NAME)
        sql = <<-EOS
          create table `#{VERSION_TABLE_NAME}` (
            `version` varchar(128),
            PRIMARY KEY (`version`)
          ) ENGINE=InnoDB DEFAULT CHARSET=utf8
        EOS
        logger.info("create #{VERSION_TABLE_NAME}")
        connection.query(sql)
      end
    end
migrate() click to toggle source
# File lib/sql_migrate/migrator.rb, line 14
def migrate
  create_migrate_versions_if_not_exist
  versions = applied_versions
  migration_files.each do |migration|
    version_name = File.basename(migration)
    next if versions.include?(version_name)
    unless config.applied
      logger.info("apply migration #{version_name}")
      queries_from_migration_file(migration).each { |sql| execute(sql) }
    end
    sql = "insert into #{VERSION_TABLE_NAME} (`version`) values (\"#{version_name}\")"
    execute(sql)
  end
end
migration_files() click to toggle source
# File lib/sql_migrate/migrator.rb, line 50
def migration_files
  config.migration_paths.map { |path|
    Dir.glob(File.join(File.expand_path(path), "*"))
  }.flatten.sort
end
table_names() click to toggle source
# File lib/sql_migrate/migrator.rb, line 42
def table_names
  connection.query("show tables", as: :array).to_a.flatten
end

Private Instance Methods

connection() click to toggle source
# File lib/sql_migrate/migrator.rb, line 72
def connection
  @connection ||= Mysql2::Client.new(**db_options)
end
db_options() click to toggle source
# File lib/sql_migrate/migrator.rb, line 76
def db_options
  options = {
    host: config.host,
    port: config.port,
    database: config.database,
    username: config.user,
  }
  options[:password] = config.password if config.password
  options
end
dryrun?() click to toggle source
# File lib/sql_migrate/migrator.rb, line 68
def dryrun?
  !!config.dryrun
end
execute(sql) click to toggle source
# File lib/sql_migrate/migrator.rb, line 58
def execute(sql)
  logger.info("execute sql:\n#{sql}") if config.verbose
  connection.query(sql) unless dryrun?
end
queries_from_migration_file(path) click to toggle source
# File lib/sql_migrate/migrator.rb, line 63
def queries_from_migration_file(path)
  migration_text = File.read(path)
  migration_text.split(";").map(&:strip).reject(&:empty?)
end