module Midnight::Rails::DefaultMigration

noinspection RubyDefParenthesesInspection noinspection RubyParameterNamingConvention

Public Instance Methods

change_event_table(\ table_name: :midnight__events, state_index_name: nil, occurred_at_index_name: nil, position_index_name: nil, concurrent_safe: false, **_ ) click to toggle source
# File lib/midnight/rails/default_migration.rb, line 34
def change_event_table(\
  table_name: :midnight__events,
  state_index_name: nil,
  occurred_at_index_name: nil,
  position_index_name: nil,
  concurrent_safe: false,
  **_
)
  # if you have an application with relatively small traffic
  # and don't have that much events to store
  # you can turn the concurrent safety on for the peace of mind
  create_table table_name do |t|
    t.binary :data, null: false
    t.binary :metadata, null: false
    t.string :event_type, null: false
    t.integer :position, null: false
    t.references :state, index: {
      name: state_index_name.presence || randomized_index_name(\
        "{#{table_name}: :state_id}"\
      )
    }
    t.datetime :occurred_at, index: {
      name: occurred_at_index_name.presence || randomized_index_name(\
        "{#{table_name}: :occurred_at}"\
      )
    }, null: false
    t.index [:state_id, :position], \
      name: position_index_name.presence || randomized_index_name(\
        "{#{table_name}:[:state_id,:position]}"\
      ), \
      unique: concurrent_safe
  end
end
change_state_table(\ table_name: :midnight__states, identification_index_name: nil, concurrent_safe: true, **_ ) click to toggle source
# File lib/midnight/rails/default_migration.rb, line 12
def change_state_table(\
  table_name: :midnight__states,
  identification_index_name: nil,
  concurrent_safe: true,
  **_
)
  # if you are sure your application don't generate aggregate_key
  # that easy to collide (e.g. running number) you can turn
  # the concurrent safety off
  create_table table_name do |t|
    t.binary :state
    t.string :aggregate_key, null: false, index: {
      name: identification_index_name.presence || randomized_index_name(
        "{#{table_name}: :aggregate_key}"
      ),
      unique: concurrent_safe
    }
    t.integer :next_position, default: 1
    t.integer :lock_version, default: 0
  end
end

Private Instance Methods

randomized_index_name(seed_data) click to toggle source
# File lib/midnight/rails/default_migration.rb, line 70
def randomized_index_name(seed_data)
  # the string can be hard coded
  # but for transparency, lets leave the origin here
  # instead of some magic constants
  randomized_part = ::OpenSSL::HMAC.hexdigest(
    'SHA256',
    'Midnight::Rails',
    seed_data
  )
  "index_rails_#{randomized_part[0, 10]}"
end