diff options
author | Sean McGivern <sean@gitlab.com> | 2019-02-05 17:41:00 +0300 |
---|---|---|
committer | Sean McGivern <sean@gitlab.com> | 2019-02-05 17:41:00 +0300 |
commit | d6be539bf1be90d81ac4ad7aac94aedebac10c43 (patch) | |
tree | 96993829bc0d4437ddf6363afa3aed710a824ea5 /doc | |
parent | 5dc15b2a3b5fee22bb905c1e178e3ea6300d02c3 (diff) | |
parent | ccd8a9b2821c964b85533c253430041712ef195e (diff) |
Merge branch 'bvl-codeowner-rules-model-ce' into 'master'
Adds helper for `find_or_create_by` in transaction
See merge request gitlab-org/gitlab-ce!24913
Diffstat (limited to 'doc')
-rw-r--r-- | doc/development/sql.md | 34 |
1 files changed, 7 insertions, 27 deletions
diff --git a/doc/development/sql.md b/doc/development/sql.md index 06005a0a6f8..47519d39e74 100644 --- a/doc/development/sql.md +++ b/doc/development/sql.md @@ -256,32 +256,12 @@ violation, for example. Using transactions does not solve this problem. -The following pattern should be used to avoid the problem: +To solve this we've added the `ApplicationRecord.safe_find_or_create_by`. -```ruby -Project.transaction do - begin - User.find_or_create_by(username: "foo") - rescue ActiveRecord::RecordNotUnique - retry - end -end -``` - -If the above block is run inside a transaction and hits the race -condition, the transaction is aborted and we cannot simply retry (any -further queries inside the aborted transaction are going to fail). We -can employ [nested transactions](http://api.rubyonrails.org/classes/ActiveRecord/Transactions/ClassMethods.html#module-ActiveRecord::Transactions::ClassMethods-label-Nested+transactions) -here to only rollback the "inner transaction". Note that `requires_new: true` is required here. +This method can be used just as you would the normal +`find_or_create_by` but it wraps the call in a *new* transaction and +retries if it were to fail because of an +`ActiveRecord::RecordNotUnique` error. -```ruby -Project.transaction do - begin - User.transaction(requires_new: true) do - User.find_or_create_by(username: "foo") - end - rescue ActiveRecord::RecordNotUnique - retry - end -end -``` +To be able to use this method, make sure the model you want to use +this on inherits from `ApplicationRecord`. |