Class: Wal::RecordWatcher::MemoryRecordWatcher

Inherits:
Object
  • Object
show all
Includes:
Watcher, Watcher::SeparatedEvents
Defined in:
lib/wal/record_watcher.rb

Instance Method Summary collapse

Methods included from Watcher::SeparatedEvents

#on_event

Methods included from Watcher

#on_event, #should_watch_table?, #valid_context_prefix?

Constructor Details

#initialize(watcher) ⇒ MemoryRecordWatcher

Returns a new instance of MemoryRecordWatcher.



161
162
163
# File 'lib/wal/record_watcher.rb', line 161

def initialize(watcher)
  @watcher = watcher
end

Instance Method Details

#on_begin(event) ⇒ Object



165
166
167
# File 'lib/wal/record_watcher.rb', line 165

def on_begin(event)
  @records = {}
end

#on_commit(_event) ⇒ Object



169
170
171
172
173
174
# File 'lib/wal/record_watcher.rb', line 169

def on_commit(_event)
  @records
    &.values
    &.lazy
    &.each { |event| @watcher.on_record_changed(event) if event }
end

#on_delete(event) ⇒ Object



203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
# File 'lib/wal/record_watcher.rb', line 203

def on_delete(event)
  if (id = event.primary_key)
    @records ||= {}
    @records[[event.full_table_name, id]] = case (existing_event = @records[[event.full_table_name, id]])
    when InsertEvent
      # We are removing a record that was inserted on this transaction, we should not even report this change, as
      # this record never existed outside this transaction anyways.
      nil

    when UpdateEvent
      # Deleting a record that was previously updated by this transaction. Just store the previous data while
      # keeping the record as deleted.
      event.with(old: existing_event.old)

    else
      event
    end
  end
end

#on_insert(event) ⇒ Object



176
177
178
179
180
181
# File 'lib/wal/record_watcher.rb', line 176

def on_insert(event)
  if (id = event.primary_key)
    @records ||= {}
    @records[[event.table, id]] = event
  end
end

#on_update(event) ⇒ Object



183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
# File 'lib/wal/record_watcher.rb', line 183

def on_update(event)
  if (id = event.primary_key)
    @records ||= {}
    @records[[event.full_table_name, id]] = case (existing_event = @records[[event.full_table_name, id]])
    when InsertEvent
      # A record inserted on this transaction is being updated, which means it should still reflect as a insert
      # event, we just change the information to reflect the most current data that was just updated.
      existing_event.with(new: event.new)

    when UpdateEvent
      # We are updating again a event that was already updated on this transaction.
      # Same as the insert, we keep the old data from the previous update and the new data from the new one.
      existing_event.with(new: event.new)

    else
      event
    end
  end
end