Commit 44212654 authored by pbair's avatar pbair

Allow nesting of SharedModel.using_connection

Allow SharedModel.using_connection to be called within nested blocks
with the same connection, for situations where we want to wrap multiple
entry points that might be called in a chain.
parent 4ba7c274
...@@ -8,13 +8,17 @@ module Gitlab ...@@ -8,13 +8,17 @@ module Gitlab
class << self class << self
def using_connection(connection) def using_connection(connection)
raise 'cannot nest connection overrides for shared models' unless overriding_connection.nil? previous_connection = self.overriding_connection
unless previous_connection.nil? || previous_connection.equal?(connection)
raise 'cannot nest connection overrides for shared models with different connections'
end
self.overriding_connection = connection self.overriding_connection = connection
yield yield
ensure ensure
self.overriding_connection = nil self.overriding_connection = nil unless previous_connection.equal?(self.overriding_connection)
end end
def connection def connection
......
...@@ -27,6 +27,38 @@ RSpec.describe Gitlab::Database::SharedModel do ...@@ -27,6 +27,38 @@ RSpec.describe Gitlab::Database::SharedModel do
end end
end end
context 'when multiple connection overrides are nested', :aggregate_failures do
let(:second_connection) { double('connection') }
it 'allows the nesting with the same connection object' do
expect_original_connection_around do
described_class.using_connection(new_connection) do
expect(described_class.connection).to be(new_connection)
described_class.using_connection(new_connection) do
expect(described_class.connection).to be(new_connection)
end
expect(described_class.connection).to be(new_connection)
end
end
end
it 'raises an error if the connection is changed' do
expect_original_connection_around do
described_class.using_connection(new_connection) do
expect(described_class.connection).to be(new_connection)
expect do
described_class.using_connection(second_connection) {}
end.to raise_error(/cannot nest connection overrides/)
expect(described_class.connection).to be(new_connection)
end
end
end
end
context 'when the block raises an error', :aggregate_failures do context 'when the block raises an error', :aggregate_failures do
it 're-raises the error, removing the overridden connection' do it 're-raises the error, removing the overridden connection' do
expect_original_connection_around do expect_original_connection_around do
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment