Fixed: Optimistic locking does not work correctly #26050
Thanks for the pull request, and welcome! The Rails team is excited to review your changes, and you should hear from @rafaelfranca (or someone else) soon.
If any changes to this PR are deemed necessary, please add them as extra commits. This ensures that the reviewer can see what has changed since they last reviewed the code. Due to the way GitHub handles out-of-date commits, this should also make it reasonably obvious what issues have or haven't been addressed. Large or tricky changes may require several passes of review and changes.
This repository is being automatically checked for code quality issues using Code Climate. You can see results for this analysis in the PR status below. Newly introduced issues should be fixed before a Pull Request is considered ready to review.
Please see the contribution instructions for more information.
There are two bugs in this functionality (rails master and 4.2.*) I prepared two test cases
require 'active_record' require 'minitest/autorun' require 'sqlite3' require 'logger' ActiveRecord::Base.establish_connection 'sqlite3::memory:' ActiveRecord::Schema.define do create_table :posts do |t| t.string :name t.integer :lock_version end end class Post < ActiveRecord::Base end class BugTest < Minitest::Test def test_lock_version_without_default_value #Post.create!(name: 'First') ActiveRecord::Base.connection.execute("insert into posts(name) VALUES('Mark')") p1 = Post.find(1) p1.name = "Michael" p1.save end def test_lock_version_without_default_value_when_form_submit ActiveRecord::Base.connection.execute("insert into posts(name) VALUES('Mark')") p1 = Post.find(1) p1.update(name: "Bob", lock_version: "0") p1.save end end
This PR fixes first one. Anyway this PR can be considered as a fix and merged separately
@vsizov are you about?
relation = relation.where(self.class.primary_key => id) relation = relation.where(lock_col => previous_lock_value) unless update_with_lock_col
In logs i see only one SQL query when running line with
relation.update_all # UPDATE "posts" SET "title" = 'new title', "lock_version" = 1 WHERE "posts"."id" = ? AND "posts"."lock_version" IS NULL
i believe in it, but I have to make sure.