Class: RedshiftConnector::Importer::RebuildRename

Inherits:
Object
  • Object
show all
Defined in:
lib/redshift_connector/importer/rebuild_rename.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(dao:, columns:, logger: RedshiftConnector.logger) ⇒ RebuildRename

Returns a new instance of RebuildRename.



7
8
9
10
11
# File 'lib/redshift_connector/importer/rebuild_rename.rb', line 7

def initialize(dao:, columns:, logger: RedshiftConnector.logger)
  @dao = dao
  @columns = columns
  @logger = logger
end

Class Method Details

.get_unique_sequenceObject



42
43
44
# File 'lib/redshift_connector/importer/rebuild_rename.rb', line 42

def self.get_unique_sequence
  @dao_seq_lock.synchronize { @dao_seq += 1 }
end

.make_temporary_dao(orig) ⇒ Object

Duplicates DAO (ActiveRecord class) and names it. Newer activerecord-import requires a class name (not a table name), we must prepare some name for temporary DAO class.



32
33
34
35
36
37
# File 'lib/redshift_connector/importer/rebuild_rename.rb', line 32

def self.make_temporary_dao(orig)
  tmp = orig.dup
  const_set("TemporaryDAO_#{get_unique_sequence}", tmp)
  tmp.name   # fix class name
  tmp
end

Instance Method Details

#exec_update(query) ⇒ Object



46
47
48
49
# File 'lib/redshift_connector/importer/rebuild_rename.rb', line 46

def exec_update(query)
  @logger.info query
  @dao.connection.execute(query)
end

#execute(bundle) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/redshift_connector/importer/rebuild_rename.rb', line 13

def execute(bundle)
  dest_table = @dao.table_name
  tmp_table = "#{dest_table}_new"
  old_table = "#{dest_table}_old"

  tmp_dao = self.class.make_temporary_dao(@dao)
  tmp_dao.table_name = tmp_table

  exec_update "drop table if exists #{tmp_table}"
  exec_update "create table #{tmp_table} like #{dest_table}"
  import(tmp_dao, bundle)
  exec_update "drop table if exists #{old_table}"
  # Atomic table exchange
  exec_update "rename table #{dest_table} to #{old_table}, #{tmp_table} to #{dest_table}"
end

#import(dao, bundle) ⇒ Object



51
52
53
54
55
56
# File 'lib/redshift_connector/importer/rebuild_rename.rb', line 51

def import(dao, bundle)
  @logger.info "IMPORT #{bundle.url}* -> #{dao.table_name} (#{@columns.join(', ')})"
  bundle.each_batch do |rows|
    dao.import(@columns, rows)
  end
end