Class: Bemi::Storage

Inherits:
Object
  • Object
show all
Defined in:
lib/bemi/storage.rb

Class Method Summary collapse

Class Method Details

.create_changeset!(payload) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/bemi/storage.rb', line 8

def create_changeset!(payload)
  puts payload.inspect
  action = payload['type']
  values_before = action == Bemi::Changeset::ACTION_DELETE ? payload['data'] : payload.fetch('old', {})
  values_after = action == Bemi::Changeset::ACTION_DELETE ? {} : payload['data']
  fields = (values_before.keys | values_after.keys).sort
  context_id = payload['query'].split('/* ')[1]&.split(' */')&.first

  Bemi::Changeset.create!(
    context_id: context_id,
    external_id: values_after['id'] || values_before['id'],
    database: payload['database'],
    table: payload['table'],
    query: payload['query'],
    action: action,
    committed_at: Time.at(payload['ts']),
    binlog_position: payload['position'],
    values_before: fields.each_with_object({}) { |f, memo| memo[f] = values_before[f] || (action == Bemi::Changeset::ACTION_UPDATE ? values_after[f] : nil) },
    values_after: fields.each_with_object({}) { |f, memo| memo[f] = values_after[f] },
  )
end

.generate_migrationObject



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/bemi/storage.rb', line 30

def generate_migration
  migration_class = Class.new(ActiveRecord::Migration[6.0])

  migration_class.class_eval do
    def change
      create_table :bemi_changesets do |t|
        t.integer :context_id, index: true
        t.string :external_id, index: true
        t.string :database, null: false
        t.string :table, null: false
        t.text :query, null: false
        t.string :action, null: false
        t.timestamp :committed_at, null: false, index: true
        t.string :binlog_position, null: false # ?
        t.json :values_before, null: false
        t.json :values_after, null: false
        t.timestamps
      end

      add_index :bemi_changesets, [:database, :table]

      create_table :bemi_contexts do |t|
        t.json :data, null: false
        t.timestamps
      end
    end
  end

  migration_class
end