Module: Switchman::ActiveRecord::Migrator

Defined in:
lib/switchman/active_record/migration.rb

Instance Method Summary collapse

Instance Method Details

#generate_migrator_advisory_lock_idObject

significant change: hash shard id, not database name



34
35
36
37
# File 'lib/switchman/active_record/migration.rb', line 34

def generate_migrator_advisory_lock_id
  shard_name_hash = Zlib.crc32(Shard.current.name)
  ::ActiveRecord::Migrator::MIGRATOR_SALT * shard_name_hash
end

#with_advisory_lockObject

copy/paste from Rails 6.1



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/switchman/active_record/migration.rb', line 41

def with_advisory_lock
  lock_id = generate_migrator_advisory_lock_id

  with_advisory_lock_connection do |connection|
    got_lock = connection.get_advisory_lock(lock_id)
    raise ::ActiveRecord::ConcurrentMigrationError unless got_lock
    load_migrated # reload schema_migrations to be sure it wasn't changed by another process before we got the lock
    yield
  ensure
    if got_lock && !connection.release_advisory_lock(lock_id)
      raise ::ActiveRecord::ConcurrentMigrationError.new(
        ::ActiveRecord::ConcurrentMigrationError::RELEASE_LOCK_FAILED_MESSAGE
      )
    end
  end
end

#with_advisory_lock_connectionObject

significant change: strip out prefer_secondary from config



59
60
61
62
63
64
65
66
67
# File 'lib/switchman/active_record/migration.rb', line 59

def with_advisory_lock_connection
  pool = ::ActiveRecord::ConnectionAdapters::ConnectionHandler.new.establish_connection(
    ::ActiveRecord::Base.connection_config.except(:prefer_secondary)
  )

  pool.with_connection { |connection| yield(connection) }
ensure
  pool&.disconnect!
end