summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorStan Hu <stanhu@gmail.com>2019-05-06 11:22:50 -0700
committerStan Hu <stanhu@gmail.com>2019-05-06 11:34:06 -0700
commit5d68399364edd49e07fcf04771dd4fb5b6e95347 (patch)
tree994460896232505242726bccd4a2a8c9ba60a2ec
parent6eb448518f4169ac5e389234f5e3d88751f553be (diff)
downloadgitlab-ce-add-spec-for-optimistic-locking-error.tar.gz
Add monkey patch to check NULL version of lock_versionadd-spec-for-optimistic-locking-error
-rw-r--r--config/initializers/config_initializers_active_record_locking.rb40
1 files changed, 40 insertions, 0 deletions
diff --git a/config/initializers/config_initializers_active_record_locking.rb b/config/initializers/config_initializers_active_record_locking.rb
new file mode 100644
index 00000000000..2a78b16d740
--- /dev/null
+++ b/config/initializers/config_initializers_active_record_locking.rb
@@ -0,0 +1,40 @@
+# rubocop:disable Lint/RescueException
+module ActiveRecord
+ module Locking
+ module Optimistic
+ private
+
+ def _update_row(attribute_names, attempted_action = "update")
+ return super unless locking_enabled?
+
+ begin
+ locking_column = self.class.locking_column
+ previous_lock_value = read_attribute_before_type_cast(locking_column)
+ attribute_names << locking_column
+
+ self[locking_column] += 1
+
+ # Patched because when `lock_version` is read as `0`, it may actually be `NULL` in the DB.
+ previous_lock_value = previous_lock_value == 0 ? [nil, 0] : previous_lock_value
+
+ affected_rows = self.class.unscoped._update_record(
+ arel_attributes_with_values(attribute_names),
+ self.class.primary_key => id_in_database,
+ locking_column => previous_lock_value
+ )
+
+ if affected_rows != 1
+ raise ActiveRecord::StaleObjectError.new(self, attempted_action)
+ end
+
+ affected_rows
+
+ # If something went wrong, revert the locking_column value.
+ rescue Exception
+ self[locking_column] = previous_lock_value.to_i
+ raise
+ end
+ end
+ end
+ end
+end