optimistic.rb 7.1 KB
Newer Older
1 2
module ActiveRecord
  module Locking
3 4
    # == What is Optimistic Locking
    #
5
    # Optimistic locking allows multiple users to access the same record for edits, and assumes a minimum of
6 7 8
    # conflicts with the data. It does this by checking whether another process has made changes to a record since
    # it was opened, an <tt>ActiveRecord::StaleObjectError</tt> exception is thrown if that has occurred
    # and the update is ignored.
9
    #
10
    # Check out <tt>ActiveRecord::Locking::Pessimistic</tt> for an alternative.
11 12 13
    #
    # == Usage
    #
14 15 16
    # Active Records support optimistic locking if the field +lock_version+ is present. Each update to the
    # record increments the +lock_version+ column and the locking facilities ensure that records instantiated twice
    # will let the last one saved raise a +StaleObjectError+ if the first was also updated. Example:
17 18 19
    #
    #   p1 = Person.find(1)
    #   p2 = Person.find(1)
20
    #
21 22
    #   p1.first_name = "Michael"
    #   p1.save
23
    #
24 25 26
    #   p2.first_name = "should fail"
    #   p2.save # Raises a ActiveRecord::StaleObjectError
    #
P
Paco Guzman 已提交
27
    # Optimistic locking will also check for stale data when objects are destroyed. Example:
28 29 30 31 32 33 34 35 36
    #
    #   p1 = Person.find(1)
    #   p2 = Person.find(1)
    #
    #   p1.first_name = "Michael"
    #   p1.save
    #
    #   p2.destroy # Raises a ActiveRecord::StaleObjectError
    #
37 38 39
    # You're then responsible for dealing with the conflict by rescuing the exception and either rolling back, merging,
    # or otherwise apply the business logic needed to resolve the conflict.
    #
40 41 42
    # This locking mechanism will function inside a single Ruby process. To make it work across all
    # web requests, the recommended approach is to add +lock_version+ as a hidden field to your form.
    #
43
    # This behavior can be turned off by setting <tt>ActiveRecord::Base.lock_optimistically = false</tt>.
44 45 46 47 48 49
    # To override the name of the +lock_version+ column, set the <tt>locking_column</tt> class attribute:
    #
    #   class Person < ActiveRecord::Base
    #     self.locking_column = :lock_person
    #   end
    #
50
    module Optimistic
51
      extend ActiveSupport::Concern
52

53
      included do
J
Jon Leighton 已提交
54 55
        class_attribute :lock_optimistically, instance_writer: false
        self.lock_optimistically = true
56
      end
57

58
      def locking_enabled? #:nodoc:
59
        self.class.locking_enabled?
60 61
      end

62
      private
63 64 65 66 67 68
        def increment_lock
          lock_col = self.class.locking_column
          previous_lock_value = send(lock_col).to_i
          send(lock_col + '=', previous_lock_value + 1)
        end

69
        def _update_record(attribute_names = self.attribute_names) #:nodoc:
70
          return super unless locking_enabled?
71
          return 0 if attribute_names.empty?
72

73
          lock_col = self.class.locking_column
74 75
          previous_lock_value = send(lock_col).to_i
          increment_lock
76

77 78 79
          attribute_names += [lock_col]
          attribute_names.uniq!

80
          begin
81
            relation = self.class.unscoped
82

83 84 85 86 87 88
            # FIXME: Remove the Arel::Nodes::Quoted when we remove type casting
            # from Arel (Rails 5.1)
            quoted_lock_value = Arel::Nodes::Quoted.new(
              self.class.quote_value(
                previous_lock_value,
                column_for_attribute(lock_col),
E
Emilio Tagua 已提交
89
              )
90 91 92 93 94
            )
            quoted_id = Arel::Nodes::Quoted.new(id)
            stmt = relation.where(
              relation.table[self.class.primary_key].eq(quoted_id).and(
                relation.table[lock_col].eq(quoted_lock_value))
A
Aaron Patterson 已提交
95 96 97 98
            ).arel.compile_update(
              arel_attributes_with_values_for_update(attribute_names),
              self.class.primary_key
            )
99

100
            affected_rows = self.class.connection.update stmt
E
Emilio Tagua 已提交
101 102

            unless affected_rows == 1
103
              raise ActiveRecord::StaleObjectError.new(self, "update")
104
            end
105

106 107 108 109
            affected_rows

          # If something went wrong, revert the version.
          rescue Exception
110
            send(lock_col + '=', previous_lock_value)
111 112
            raise
          end
113
        end
114

115 116 117 118 119 120
        def destroy_row
          affected_rows = super

          if locking_enabled? && affected_rows != 1
            raise ActiveRecord::StaleObjectError.new(self, "destroy")
          end
121

122 123
          affected_rows
        end
124

125 126
        def relation_for_destroy
          relation = super
P
Pratik Naik 已提交
127

128 129 130
          if locking_enabled?
            column_name = self.class.locking_column
            column      = self.class.columns_hash[column_name]
131
            substitute  = self.class.connection.substitute_at(column)
132

133 134
            relation = relation.where(self.class.arel_table[column_name].eq(substitute))
            relation.bind_values << [column, self[column_name].to_i]
135 136
          end

137
          relation
138 139
        end

140 141
      module ClassMethods
        DEFAULT_LOCKING_COLUMN = 'lock_version'
142

143 144 145
        # Returns true if the +lock_optimistically+ flag is set to true
        # (which it is, by default) and the table includes the
        # +locking_column+ column (defaults to +lock_version+).
146 147 148 149
        def locking_enabled?
          lock_optimistically && columns_hash[locking_column]
        end

150
        # Set the column to use for optimistic locking. Defaults to +lock_version+.
151
        def locking_column=(value)
152
          clear_caches_calculated_from_columns
J
Jon Leighton 已提交
153
          @locking_column = value.to_s
154 155
        end

P
Pratik Naik 已提交
156
        # The version column used for optimistic locking. Defaults to +lock_version+.
157
        def locking_column
158 159 160 161
          reset_locking_column unless defined?(@locking_column)
          @locking_column
        end

P
Pratik Naik 已提交
162
        # Reset the column used for optimistic locking back to the +lock_version+ default.
163
        def reset_locking_column
164
          self.locking_column = DEFAULT_LOCKING_COLUMN
165
        end
166

P
Pratik Naik 已提交
167
        # Make sure the lock version column gets updated when counters are
168
        # updated.
169
        def update_counters(id, counters)
170
          counters = counters.merge(locking_column => 1) if locking_enabled?
171
          super
172
        end
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188

        private

        # We need to apply this decorator here, rather than on module inclusion. The closure
        # created by the matcher would otherwise evaluate for `ActiveRecord::Base`, not the
        # sub class being decorated. As such, changes to `lock_optimistically`, or
        # `locking_column` would not be picked up.
        def inherited(subclass)
          subclass.class_eval do
            is_lock_column = ->(name, _) { lock_optimistically && name == locking_column }
            decorate_matching_attribute_types(is_lock_column, :_optimistic_locking) do |type|
              LockingType.new(type)
            end
          end
          super
        end
189 190
      end
    end
191

192
    class LockingType < SimpleDelegator # :nodoc:
193 194 195 196
      def type_cast_from_database(value)
        # `nil` *should* be changed to 0
        super.to_i
      end
197

198 199 200 201
      def changed?(old_value, *)
        # Ensure we save if the default was `nil`
        super || old_value == 0
      end
202

203 204 205 206 207 208
      def init_with(coder)
        __setobj__(coder['subtype'])
      end

      def encode_with(coder)
        coder['subtype'] = __getobj__
209 210
      end
    end
211
  end
212
end