transactions.rb 4.8 KB
Newer Older
D
Initial  
David Heinemeier Hansson 已提交
1 2 3 4
require 'thread'

module ActiveRecord
  module Transactions # :nodoc:
5 6 7
    class TransactionError < ActiveRecordError # :nodoc:
    end

8
    def self.included(base)
D
Initial  
David Heinemeier Hansson 已提交
9 10 11
      base.extend(ClassMethods)

      base.class_eval do
12
        [:destroy, :save, :save!].each do |method|
13 14
          alias_method_chain method, :transactions
        end
D
Initial  
David Heinemeier Hansson 已提交
15 16 17
      end
    end

18
    # Transactions are protective blocks where SQL statements are only permanent if they can all succeed as one atomic action.
19
    # The classic example is a transfer between two accounts where you can only have a deposit if the withdrawal succeeded and
D
David Heinemeier Hansson 已提交
20
    # vice versa. Transactions enforce the integrity of the database and guard the data against program errors or database break-downs.
D
Initial  
David Heinemeier Hansson 已提交
21 22 23 24 25 26 27 28 29 30
    # So basically you should use transaction blocks whenever you have a number of statements that must be executed together or
    # not at all. Example:
    #
    #   transaction do
    #     david.withdrawal(100)
    #     mary.deposit(100)
    #   end
    #
    # This example will only take money from David and give to Mary if neither +withdrawal+ nor +deposit+ raises an exception.
    # Exceptions will force a ROLLBACK that returns the database to the state before the transaction was begun. Be aware, though,
P
Pratik Naik 已提交
31
    # that the objects will _not_ have their instance data returned to their pre-transactional state.
D
Initial  
David Heinemeier Hansson 已提交
32
    #
33 34 35 36 37 38 39 40 41
    # == Different ActiveRecord classes in a single transaction
    #
    # Though the transaction class method is called on some ActiveRecord class,
    # the objects within the transaction block need not all be instances of
    # that class.
    # In this example a <tt>Balance</tt> record is transactionally saved even
    # though <tt>transaction</tt> is called on the <tt>Account</tt> class:
    #
    #   Account.transaction do
42 43
    #     balance.save!
    #     account.save!
44 45
    #   end
    #
D
Initial  
David Heinemeier Hansson 已提交
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
    # == Transactions are not distributed across database connections
    #
    # A transaction acts on a single database connection.  If you have
    # multiple class-specific databases, the transaction will not protect
    # interaction among them.  One workaround is to begin a transaction
    # on each class whose models you alter:
    #
    #   Student.transaction do
    #     Course.transaction do
    #       course.enroll(student)
    #       student.units += course.units
    #     end
    #   end
    #
    # This is a poor solution, but full distributed transactions are beyond
    # the scope of Active Record.
    #
    # == Save and destroy are automatically wrapped in a transaction
    #
    # Both Base#save and Base#destroy come wrapped in a transaction that ensures that whatever you do in validations or callbacks
    # will happen under the protected cover of a transaction. So you can use validations to check for values that the transaction
67
    # depends on or you can raise exceptions in the callbacks to rollback.
D
Initial  
David Heinemeier Hansson 已提交
68 69 70 71
    #
    # == Exception handling
    #
    # Also have in mind that exceptions thrown within a transaction block will be propagated (after triggering the ROLLBACK), so you
72 73
    # should be ready to catch those in your application code. One exception is the ActiveRecord::Rollback exception, which will
    # trigger a ROLLBACK when raised, but not be re-raised by the transaction block.
74
    module ClassMethods
75
      def transaction(&block)
76 77
        increment_open_transactions

D
Initial  
David Heinemeier Hansson 已提交
78
        begin
79
          connection.transaction(Thread.current['start_db_transaction'], &block)
D
Initial  
David Heinemeier Hansson 已提交
80
        ensure
81
          decrement_open_transactions
D
Initial  
David Heinemeier Hansson 已提交
82 83
        end
      end
84 85 86 87 88 89 90 91 92 93 94

      private
        def increment_open_transactions #:nodoc:
          open = Thread.current['open_transactions'] ||= 0
          Thread.current['start_db_transaction'] = open.zero?
          Thread.current['open_transactions'] = open + 1
        end

        def decrement_open_transactions #:nodoc:
          Thread.current['open_transactions'] -= 1
        end
D
Initial  
David Heinemeier Hansson 已提交
95 96
    end

97 98
    def transaction(&block)
      self.class.transaction(&block)
D
Initial  
David Heinemeier Hansson 已提交
99 100 101
    end

    def destroy_with_transactions #:nodoc:
102
      transaction { destroy_without_transactions }
D
Initial  
David Heinemeier Hansson 已提交
103
    end
104

D
Initial  
David Heinemeier Hansson 已提交
105
    def save_with_transactions(perform_validation = true) #:nodoc:
106
      rollback_active_record_state! { transaction { save_without_transactions(perform_validation) } }
D
Initial  
David Heinemeier Hansson 已提交
107
    end
108 109

    def save_with_transactions! #:nodoc:
110
      rollback_active_record_state! { transaction { save_without_transactions! } }
111
    end
112 113 114 115 116

    # Reset id and @new_record if the transaction rolls back.
    def rollback_active_record_state!
      id_present = has_attribute?(self.class.primary_key)
      previous_id = id
117
      previous_new_record = new_record?
118 119 120 121
      yield
    rescue Exception
      @new_record = previous_new_record
      if id_present
122
        self.id = previous_id
123 124
      else
        @attributes.delete(self.class.primary_key)
125
        @attributes_cache.delete(self.class.primary_key)
126
      end
127
      raise
128
    end
D
Initial  
David Heinemeier Hansson 已提交
129
  end
130
end