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: just return MIGRATOR_SALT directly especially if you’re going through pgbouncer, the database name you’re accessing may not be consistent. it is NOT allowed to run migrations against multiple shards in the same database concurrently



38
39
40
# File 'lib/switchman/active_record/migration.rb', line 38

def generate_migrator_advisory_lock_id
  ::ActiveRecord::Migrator::MIGRATOR_SALT
end

#with_advisory_lockObject

copy/paste from Rails 6.1



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

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



62
63
64
65
66
67
68
69
70
# File 'lib/switchman/active_record/migration.rb', line 62

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