Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does activerecord optimistic locking work only once per row?

Somehow, I always get these on Fridays.

My earlier question was regarding the same problem, but I can now narrow things down a bit:

I've been playing with this all day, trying to make sense of it. I have a table with a lock_version colum, specified thus:

add_column :jobs, :lock_version, :integer, :default=>0

And I do something like this:

foo = job.create!
first = Job.find(foo.id)
second = Job.find(foo.id)

I then verify that first and second refer to the same object - their ids are the same and I see that row in the database using the mysql command-line tool.

first.some_attribute_field = 'first'
second.some_attribute_field = 'second'
first.save
second.save

no problem so far. I correctly get an ActiveRecord::StaleObjectError exception. HOWEVER:

first = Job.find(foo.id)
second = Job.find(foo.id)
first.some_attribute_field = 'first'
second.some_attribute_field = 'second'
first.save
second.save

...and nothing happens. It turns out that the only time I get correct (thrown exception) behavior is when first and second have a lock_version of 0. After the first save, though, it is NEVER 0 again. What on earth is up with this?

I'm using ruby 1.8.6 and active record 2.2.2

Thanks...

like image 635
Sniggerfardimungus Avatar asked May 01 '09 22:05

Sniggerfardimungus


1 Answers

when you call first.save the second time the value of some_attribute_field is already equal to "first", activerecord knows this so it doesn't update in the db to lock_version doesn't get incremented. The second save works as the db was never changed with the "first".

Try changing the value in the second test to something other than "first" so that it is different to what is in the db.

like image 180
Osseta Avatar answered Nov 07 '22 18:11

Osseta