Class: Micdrop::Ext::Sequel::InsertUpdateSink

Inherits:
Object
  • Object
show all
Defined in:
lib/micdrop/ext/sequel.rb

Overview

A sink which will update an item if it exists, or insert it otherwise

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(dataset, key_columns, update_actions: {}, default_update_action: :coalesce, match_empty_key: false) ⇒ InsertUpdateSink

Returns a new instance of InsertUpdateSink.



47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/micdrop/ext/sequel.rb', line 47

def initialize(dataset, key_columns, update_actions: {}, default_update_action: :coalesce,
               match_empty_key: false)
  @dataset = dataset
  @key_columns = if key_columns.is_a? Symbol
                   [key_columns]
                 elsif key_columns.respond_to? :each
                   key_columns
                   # TODO: else throw error
                 end
  @update_actions = update_actions
  @default_update_action = default_update_action
  @match_empty_key = match_empty_key
end

Instance Attribute Details

#insert_idObject (readonly)

Returns the value of attribute insert_id.



61
62
63
# File 'lib/micdrop/ext/sequel.rb', line 61

def insert_id
  @insert_id
end

#was_insertObject (readonly)

Returns the value of attribute was_insert.



61
62
63
# File 'lib/micdrop/ext/sequel.rb', line 61

def was_insert
  @was_insert
end

Instance Method Details

#<<(collector) ⇒ Object



63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/micdrop/ext/sequel.rb', line 63

def <<(collector)
  dataset = @dataset
  @key_columns.each do |col|
    dataset = dataset.where(**{ col => collector[col] })
  end
  existing = dataset.limit(2).all
  if existing.count > 1
    raise Micdrop::SinkError, "Key column(s) of this InsertUpdateSink are not unique"
  elsif existing.empty?
    @insert_id = dataset.insert(**collector)
    @was_insert = true
  else
    dataset.update(**update_merge(existing.first, collector))
    @insert_id = nil
    @was_insert = false
  end
end