/vendor/bundle/ruby/1.9.1/gems/activerecord-3.0.0/lib/active_record/locking/pessimistic.rb

https://github.com/bublanina/masterlanguage · Ruby · 56 lines · 10 code · 0 blank · 46 comment · 0 complexity · 1cdfaeb69571244c309884103854f915 MD5 · raw file

  1. # -*- encoding : utf-8 -*-
  2. module ActiveRecord
  3. module Locking
  4. # Locking::Pessimistic provides support for row-level locking using
  5. # SELECT ... FOR UPDATE and other lock types.
  6. #
  7. # Pass <tt>:lock => true</tt> to ActiveRecord::Base.find to obtain an exclusive
  8. # lock on the selected rows:
  9. # # select * from accounts where id=1 for update
  10. # Account.find(1, :lock => true)
  11. #
  12. # Pass <tt>:lock => 'some locking clause'</tt> to give a database-specific locking clause
  13. # of your own such as 'LOCK IN SHARE MODE' or 'FOR UPDATE NOWAIT'.
  14. #
  15. # Example:
  16. # Account.transaction do
  17. # # select * from accounts where name = 'shugo' limit 1 for update
  18. # shugo = Account.find(:first, :conditions => "name = 'shugo'", :lock => true)
  19. # yuko = Account.find(:first, :conditions => "name = 'yuko'", :lock => true)
  20. # shugo.balance -= 100
  21. # shugo.save!
  22. # yuko.balance += 100
  23. # yuko.save!
  24. # end
  25. #
  26. # You can also use ActiveRecord::Base#lock! method to lock one record by id.
  27. # This may be better if you don't need to lock every row. Example:
  28. # Account.transaction do
  29. # # select * from accounts where ...
  30. # accounts = Account.find(:all, :conditions => ...)
  31. # account1 = accounts.detect { |account| ... }
  32. # account2 = accounts.detect { |account| ... }
  33. # # select * from accounts where id=? for update
  34. # account1.lock!
  35. # account2.lock!
  36. # account1.balance -= 100
  37. # account1.save!
  38. # account2.balance += 100
  39. # account2.save!
  40. # end
  41. #
  42. # Database-specific information on row locking:
  43. # MySQL: http://dev.mysql.com/doc/refman/5.1/en/innodb-locking-reads.html
  44. # PostgreSQL: http://www.postgresql.org/docs/8.1/interactive/sql-select.html#SQL-FOR-UPDATE-SHARE
  45. module Pessimistic
  46. # Obtain a row lock on this record. Reloads the record to obtain the requested
  47. # lock. Pass an SQL locking clause to append the end of the SELECT statement
  48. # or pass true for "FOR UPDATE" (the default, an exclusive row lock). Returns
  49. # the locked record.
  50. def lock!(lock = true)
  51. reload(:lock => lock) unless new_record?
  52. self
  53. end
  54. end
  55. end
  56. end