On 19/11/2010, at 9:04 AM, Dmytrii Nagirniak wrote: > On 19 November 2010 08:47, Korny Sietsma <[email protected]> wrote: > You should still think carefully about what it is you are trying to do. > If you just catch the optimistic locking exception, and automatically reload > and save, then you are ensuring the second user's change overwrites the > first. The second user will never see the first user's change. That's not > really optimistic locking at all. > Yep. And this is how AR (basically most of ORMs) works by default - last > wins. Nothing to do with the locking. > Wondering why not just use a proper database transaction if atomicity is a > requirement?
Well as Korny was saying transactions and row locking won't help you if both data sets are valid. Simplistic model, but you could do this with a person record. First user is updating the phone from invalid data to something, second user is updating the address from blank to something. However, the second user sees there is invalid data in the phone number field and decides to be a good citizen and remove the invalid data, making it blank. With transactions you guarantee that both actions run, completely. So if the transactions hit the database as: First User Second User The result would be that the phone number is blank and the address has been updated. If they run: Second User First User The result is what we want, both phone number and address have been updated. This is handling merge conflicts, and a good way to do this is row version locking and reloading data before committing: When the first user reads the record, the person object has a version of "1" The second user reads the record at the same time and the person object also has a version of "1" The first user submits his changes to the phone number, and the object before save, inside a transaction, reads the row and makes sure the version number is still 1. It is, so it commits the changes, increments the version number to "2" and then commits the transaction. The second user then submits his updates, the person model does the same thing, opens a transaction, reloads the row, finds the version number has changed, and then aborts and shows the new data to the user at which point the process can repeat. Fun stuff if you don't catch it. Mikel Lindsaar http://rubyx.com/ http://lindsaar.net/ -- You received this message because you are subscribed to the Google Groups "Ruby or Rails Oceania" group. To post to this group, send email to [email protected]. To unsubscribe from this group, send email to [email protected]. For more options, visit this group at http://groups.google.com/group/rails-oceania?hl=en.
