Method: ActiveDataFrame::Row#patch

Defined in:
lib/active_data_frame/row.rb

#patch(from, values) ⇒ Object



65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
# File 'lib/active_data_frame/row.rb', line 65

def patch(from, values)
  to     = (from + values.length) - 1
  bounds = get_bounds(from, to)

  new_blocks = Hash.new do |h, k|
    h[k] = [[0] * block_type::BLOCK_SIZE, self.instance.id]
  end

  deleted_indices = []

  existing = blocks_between([bounds]).pluck(:data_frame_id, :period_index, *block_type::COLUMNS).map do |id, period_index, *block_values|
    [period_index, [block_values, id]]
  end.to_h

  iterate_bounds([bounds]) do |index, left, right, cursor, size|
    chunk = values[cursor...cursor + size]
    if existing[index]
      block = existing[index]
      block.first[left..right] = chunk.to_a
      if block.first.all?(&:zero?)
        deleted_indices << index
        existing.delete(index)
      end
    elsif chunk.any?(&:nonzero?)
      new_blocks[index].first[left..right] = chunk.to_a
    end
  end

  database.bulk_delete(self.instance.id, deleted_indices) unless deleted_indices.size.zero?
  database.bulk_update(existing)       unless existing.size.zero?
  database.bulk_insert(new_blocks)     unless new_blocks.size.zero?
  values
end