From 208338fde6750ad327fb8ab57877869435520436 Mon Sep 17 00:00:00 2001 From: Patrick Bajao Date: Fri, 12 Apr 2019 12:19:45 +0800 Subject: Add ApplicationRecord#safe_ensure_unique method Port of https://dev.gitlab.org/gitlab/gitlab-ee/merge_requests/866 to CE excluding the migration and service changes as they don't apply to CE. --- app/models/application_record.rb | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) (limited to 'app/models/application_record.rb') diff --git a/app/models/application_record.rb b/app/models/application_record.rb index 6976185264e..348468197bf 100644 --- a/app/models/application_record.rb +++ b/app/models/application_record.rb @@ -15,6 +15,19 @@ class ApplicationRecord < ActiveRecord::Base where(nil).pluck(self.primary_key) end + def self.safe_ensure_unique(retries: 0) + transaction(requires_new: true) do + yield + end + rescue ActiveRecord::RecordNotUnique + if retries > 0 + retries -= 1 + retry + end + + false + end + def self.safe_find_or_create_by!(*args) safe_find_or_create_by(*args).tap do |record| record.validate! unless record.persisted? @@ -22,10 +35,8 @@ class ApplicationRecord < ActiveRecord::Base end def self.safe_find_or_create_by(*args) - transaction(requires_new: true) do + safe_ensure_unique(retries: 1) do find_or_create_by(*args) end - rescue ActiveRecord::RecordNotUnique - retry end end -- cgit v1.2.3