Class: StagingTable::TransferStrategies::Insert

Inherits:
Object
  • Object
show all
Defined in:
lib/staging_table/transfer_strategies/insert.rb

Instance Method Summary collapse

Constructor Details

#initialize(source_model, staging_model, options = {}) ⇒ Insert

Returns a new instance of Insert.



6
7
8
9
10
11
# File 'lib/staging_table/transfer_strategies/insert.rb', line 6

def initialize(source_model, staging_model, options = {})
  @source_model = source_model
  @staging_model = staging_model
  @options = options
  @connection = source_model.connection
end

Instance Method Details

#transferObject



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/staging_table/transfer_strategies/insert.rb', line 13

def transfer
  staged_count = @staging_model.count
  return TransferResult.new if staged_count.zero?

  columns = @staging_model.column_names.map { |c| @connection.quote_column_name(c) }.join(", ")
  source_table = @connection.quote_table_name(@source_model.table_name)
  staging_table = @connection.quote_table_name(@staging_model.table_name)

  sql = <<~SQL
    INSERT INTO #{source_table} (#{columns})
    SELECT #{columns} FROM #{staging_table}
  SQL

  @connection.execute(sql)

  # For plain INSERT, all staged records are inserted (assuming no constraint violations)
  TransferResult.new(inserted: staged_count)
end