Sha256: e0e7b50073176789a6e5a35c2e5738a51e79c300fc7f92c3e8de50d8c0bcaf10

Contents?: true

Size: 1.16 KB

Versions: 2

Compression:

Stored size: 1.16 KB

Contents

# frozen_string_literal: true

module ActiveRecord # :nodoc:
  # This is monkeypatching Active Record to ensure that whenever a new connection is established it
  # switches to the same tenant as before the connection switching. This problem is more evident when
  # using read replica in Rails 6
  module ConnectionHandling
    if ActiveRecord.version.release <= Gem::Version.new('6.2')
      def connected_to_with_tenant(database: nil, role: nil, prevent_writes: false, &blk)
        current_tenant = Apartment::Tenant.current

        connected_to_without_tenant(database: database, role: role, prevent_writes: prevent_writes) do
          Apartment::Tenant.switch!(current_tenant)
          yield(blk)
        end
      end
    else
      def connected_to_with_tenant(role: nil, shard: nil, prevent_writes: false, &blk)
        current_tenant = Apartment::Tenant.current

        connected_to_without_tenant(role: role, shard: shard, prevent_writes: prevent_writes) do
          Apartment::Tenant.switch!(current_tenant)
          yield(blk)
        end
      end
    end

    alias connected_to_without_tenant connected_to
    alias connected_to connected_to_with_tenant
  end
end

Version data entries

2 entries across 2 versions & 2 rubygems

Version Path
ros-apartment-3.2.0 lib/apartment/active_record/connection_handling.rb
synerma-apartment-3.1.0 lib/apartment/active_record/connection_handling.rb