Commit 68607e07 authored by Dylan Griffith's avatar Dylan Griffith

Merge branch '338862-reduce-subtransactions-in-shard' into 'master'

Change Shard to use safe_find_or_create_by

See merge request gitlab-org/gitlab!68529
parents 7e0f618a 7c032c47
......@@ -18,10 +18,6 @@ class Shard < ApplicationRecord
end
def self.by_name(name)
transaction(requires_new: true) do
find_or_create_by(name: name)
end
rescue ActiveRecord::RecordNotUnique
retry
safe_find_or_create_by(name: name)
end
end
......@@ -33,19 +33,21 @@ RSpec.describe Shard do
expect(result.name).to eq('foo')
end
it 'retries if creation races' do
it 'returns existing record if creation races' do
shard_created_by_others = double(described_class)
expect(described_class)
.to receive(:find_or_create_by)
.with(name: 'default')
.and_raise(ActiveRecord::RecordNotUnique, 'fail')
.once
.to receive(:find_by)
.with(name: 'new_shard')
.and_return(nil, shard_created_by_others)
expect(described_class)
.to receive(:find_or_create_by)
.with(name: 'default')
.and_call_original
.to receive(:create)
.with(name: 'new_shard')
.and_raise(ActiveRecord::RecordNotUnique, 'fail')
.once
expect(described_class.by_name('default')).to eq(default_shard)
expect(described_class.by_name('new_shard')).to eq(shard_created_by_others)
end
end
end
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