Class: MysqlRewinder::Cleaner

Inherits:
Object
  • Object
show all
Defined in:
lib/mysql_rewinder/cleaner.rb,
lib/mysql_rewinder/cleaner/adapter.rb,
lib/mysql_rewinder/cleaner/mysql2_adapter.rb,
lib/mysql_rewinder/cleaner/trilogy_adapter.rb

Defined Under Namespace

Classes: Adapter, Mysql2Adapter, TrilogyAdapter

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(db_config, except_tables:, adapter:, logger: nil) ⇒ Cleaner

Returns a new instance of Cleaner.



9
10
11
12
13
14
# File 'lib/mysql_rewinder/cleaner.rb', line 9

def initialize(db_config, except_tables:, adapter:, logger: nil)
  @db_config = db_config
  @client = Adapter.generate(adapter, db_config.transform_keys(&:to_sym))
  @except_tables = except_tables
  @logger = logger
end

Instance Attribute Details

#db_configObject (readonly)

Returns the value of attribute db_config.



7
8
9
# File 'lib/mysql_rewinder/cleaner.rb', line 7

def db_config
  @db_config
end

Instance Method Details

#all_tablesObject



32
33
34
35
36
37
38
# File 'lib/mysql_rewinder/cleaner.rb', line 32

def all_tables
  @all_tables ||= @client.query(<<~SQL).flatten
    SELECT TABLE_NAME
    FROM INFORMATION_SCHEMA.TABLES
    WHERE TABLE_SCHEMA = DATABASE()
  SQL
end

#clean(tables:) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
# File 'lib/mysql_rewinder/cleaner.rb', line 20

def clean(tables:)
  target_tables = (tables - @except_tables) & all_tables

  if target_tables.empty?
    @logger&.debug { "[MysqlRewinder][#{@db_config[:database]}] Skip DELETE query because target_table is empty. tables: #{tables}, @except_tables: #{@except_tables}, all_tables: #{all_tables}." }
    return
  end

  log_and_execute("SET FOREIGN_KEY_CHECKS = 0;")
  log_and_execute(target_tables.map { |table| "DELETE FROM #{table}" }.join(';'))
end

#clean_allObject



16
17
18
# File 'lib/mysql_rewinder/cleaner.rb', line 16

def clean_all
  clean(tables: all_tables)
end