summaryrefslogtreecommitdiff
path: root/app
diff options
context:
space:
mode:
authorPatrick Bajao <ebajao@gitlab.com>2019-04-12 12:19:45 +0800
committerPatrick Bajao <ebajao@gitlab.com>2019-04-12 12:42:20 +0800
commitf103b1e7d4d83ba4b7d1b43bb7d0a0320b4b8f35 (patch)
treee8a833cfcaf5847860e299ada6256386c86e5255 /app
parent5c46af40687ae7529c33211464724f909051eb05 (diff)
downloadgitlab-ce-f103b1e7d4d83ba4b7d1b43bb7d0a0320b4b8f35.tar.gz
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.
Diffstat (limited to 'app')
-rw-r--r--app/models/application_record.rb17
1 files changed, 14 insertions, 3 deletions
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