Class: StagingTable::BulkInserter
- Inherits:
-
Object
- Object
- StagingTable::BulkInserter
- Defined in:
- lib/staging_table/bulk_inserter.rb
Instance Attribute Summary collapse
-
#batch_size ⇒ Object
readonly
Returns the value of attribute batch_size.
-
#model ⇒ Object
readonly
Returns the value of attribute model.
Instance Method Summary collapse
-
#initialize(model, batch_size: 1000) ⇒ BulkInserter
constructor
A new instance of BulkInserter.
- #insert(records) ⇒ Object
Constructor Details
#initialize(model, batch_size: 1000) ⇒ BulkInserter
Returns a new instance of BulkInserter.
7 8 9 10 |
# File 'lib/staging_table/bulk_inserter.rb', line 7 def initialize(model, batch_size: 1000) @model = model @batch_size = batch_size end |
Instance Attribute Details
#batch_size ⇒ Object (readonly)
Returns the value of attribute batch_size.
5 6 7 |
# File 'lib/staging_table/bulk_inserter.rb', line 5 def batch_size @batch_size end |
#model ⇒ Object (readonly)
Returns the value of attribute model.
5 6 7 |
# File 'lib/staging_table/bulk_inserter.rb', line 5 def model @model end |
Instance Method Details
#insert(records) ⇒ Object
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
# File 'lib/staging_table/bulk_inserter.rb', line 12 def insert(records) return if records.empty? unless records.all? { |r| r.is_a?(Hash) } raise RecordError, "All records must be hashes. If passing ActiveRecord objects, use Session#insert which normalizes them automatically." end columns = records.first.keys.map(&:to_s) quoted_columns = columns.map { |c| connection.quote_column_name(c) }.join(", ") quoted_table = connection.quote_table_name(model.table_name) records.each_slice(batch_size) do |batch| values_list = batch.map do |record| "(" + columns.map { |col| quote(record.key?(col.to_sym) ? record[col.to_sym] : record[col]) }.join(", ") + ")" end.join(", ") sql = "INSERT INTO #{quoted_table} (#{quoted_columns}) VALUES #{values_list}" connection.execute(sql) end end |