database_statements.rb 11.9 KB
Newer Older
1 2 3
module ActiveRecord
  module ConnectionAdapters # :nodoc:
    module DatabaseStatements
4 5
      # Returns an array of record hashes with the column names as keys and
      # column values as values.
6
      def select_all(sql, name = nil)
7
        select(sql, name)
8
      end
9

10 11
      # Returns a record hash with the column names as keys and column values
      # as values.
12
      def select_one(sql, name = nil)
13
        result = select_all(sql, name)
14
        result.first if result
15
      end
16 17 18

      # Returns a single value from a record
      def select_value(sql, name = nil)
19 20 21
        if result = select_one(sql, name)
          result.values.first
        end
22 23 24 25 26
      end

      # Returns an array of the values of the first column in a select:
      #   select_values("SELECT id FROM companies LIMIT 3") => [1,2,3]
      def select_values(sql, name = nil)
27 28
        result = select_rows(sql, name)
        result.map { |v| v[0] }
29 30
      end

31
      # Returns an array of arrays containing the field values.
P
Pratik Naik 已提交
32
      # Order is the same as that returned by +columns+.
33 34
      def select_rows(sql, name = nil)
      end
35
      undef_method :select_rows
36

37
      # Executes the SQL statement in the context of this connection.
A
Aaron Patterson 已提交
38
      def execute(sql, name = nil)
39
      end
40
      undef_method :execute
41 42

      # Returns the last auto-generated ID from the affected table.
43
      def insert(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil)
44
        insert_sql(sql, name, pk, id_value, sequence_name)
45
      end
46 47

      # Executes the update statement and returns the number of rows affected.
48
      def update(sql, name = nil)
49
        update_sql(sql, name)
50
      end
51 52

      # Executes the delete statement and returns the number of rows affected.
53
      def delete(sql, name = nil)
54
        delete_sql(sql, name)
55
      end
56

57 58 59 60 61 62 63 64 65 66 67 68 69
      # Checks whether there is currently no transaction active. This is done
      # by querying the database driver, and does not use the transaction
      # house-keeping information recorded by #increment_open_transactions and
      # friends.
      #
      # Returns true if there is no transaction active, false if there is a
      # transaction active, and nil if this information is unknown.
      #
      # Not all adapters supports transaction state introspection. Currently,
      # only the PostgreSQL adapter supports this.
      def outside_transaction?
        nil
      end
70

71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
      # Runs the given block in a database transaction, and returns the result
      # of the block.
      #
      # == Nested transactions support
      #
      # Most databases don't support true nested transactions. At the time of
      # writing, the only database that supports true nested transactions that
      # we're aware of, is MS-SQL.
      #
      # In order to get around this problem, #transaction will emulate the effect
      # of nested transactions, by using savepoints:
      # http://dev.mysql.com/doc/refman/5.0/en/savepoints.html
      # Savepoints are supported by MySQL and PostgreSQL, but not SQLite3.
      #
      # It is safe to call this method if a database transaction is already open,
      # i.e. if #transaction is called within another #transaction block. In case
      # of a nested call, #transaction will behave as follows:
      #
      # - The block will be run without doing anything. All database statements
      #   that happen within the block are effectively appended to the already
      #   open database transaction.
92
      # - However, if +:requires_new+ is set, the block will be wrapped in a
93
      #   database savepoint acting as a sub-transaction.
94 95 96 97 98 99 100 101 102 103 104 105 106 107
      #
      # === Caveats
      #
      # MySQL doesn't support DDL transactions. If you perform a DDL operation,
      # then any created savepoints will be automatically released. For example,
      # if you've created a savepoint, then you execute a CREATE TABLE statement,
      # then the savepoint that was created will be automatically released.
      #
      # This means that, on MySQL, you shouldn't execute DDL operations inside
      # a #transaction call that you know might create a savepoint. Otherwise,
      # #transaction will raise exceptions when it tries to release the
      # already-automatically-released savepoints:
      #
      #   Model.connection.transaction do  # BEGIN
108
      #     Model.connection.transaction(:requires_new => true) do  # CREATE SAVEPOINT active_record_1
109
      #       Model.connection.create_table(...)
110 111
      #       # active_record_1 now automatically released
      #     end  # RELEASE SAVEPOINT active_record_1  <--- BOOM! database error!
112
      #   end
113 114 115
      def transaction(options = {})
        options.assert_valid_keys :requires_new, :joinable

116
        last_transaction_joinable = defined?(@transaction_joinable) ? @transaction_joinable : nil
117 118 119 120 121
        if options.has_key?(:joinable)
          @transaction_joinable = options[:joinable]
        else
          @transaction_joinable = true
        end
122 123
        requires_new = options[:requires_new] || !last_transaction_joinable

124
        transaction_open = false
125 126
        @_current_transaction_records ||= []

127 128
        begin
          if block_given?
129
            if requires_new || open_transactions == 0
130 131
              if open_transactions == 0
                begin_db_transaction
132
              elsif requires_new
133 134
                create_savepoint
              end
J
Jonathan Viney 已提交
135
              increment_open_transactions
136
              transaction_open = true
137
              @_current_transaction_records.push([])
138
            end
139
            yield
140
          end
141
        rescue Exception => database_transaction_rollback
142
          if transaction_open && !outside_transaction?
143
            transaction_open = false
J
Jonathan Viney 已提交
144
            decrement_open_transactions
145 146
            if open_transactions == 0
              rollback_db_transaction
147
              rollback_transaction_records(true)
148 149
            else
              rollback_to_savepoint
150
              rollback_transaction_records(false)
151
            end
152
          end
153
          raise unless database_transaction_rollback.is_a?(ActiveRecord::Rollback)
154
        end
155
      ensure
156 157
        @transaction_joinable = last_transaction_joinable

158 159 160
        if outside_transaction?
          @open_transactions = 0
        elsif transaction_open
J
Jonathan Viney 已提交
161
          decrement_open_transactions
162
          begin
163 164
            if open_transactions == 0
              commit_db_transaction
165
              commit_transaction_records
166 167
            else
              release_savepoint
168 169 170 171 172
              save_point_records = @_current_transaction_records.pop
              unless save_point_records.blank?
                @_current_transaction_records.push([]) if @_current_transaction_records.empty?
                @_current_transaction_records.last.concat(save_point_records)
              end
173
            end
174
          rescue Exception => database_transaction_rollback
175 176
            if open_transactions == 0
              rollback_db_transaction
177
              rollback_transaction_records(true)
178 179
            else
              rollback_to_savepoint
180
              rollback_transaction_records(false)
181
            end
182 183 184
            raise
          end
        end
185
      end
186

187 188 189 190 191 192 193
      # Register a record with the current transaction so that its after_commit and after_rollback callbacks
      # can be called.
      def add_transaction_record(record)
        last_batch = @_current_transaction_records.last
        last_batch << record if last_batch
      end

194 195 196 197 198 199
      # Begins the transaction (and turns off auto-committing).
      def begin_db_transaction()    end

      # Commits the transaction (and turns on auto-committing).
      def commit_db_transaction()   end

200 201
      # Rolls back the transaction (and turns on auto-committing). Must be
      # done if the transaction block raises an exception or returns false.
202 203
      def rollback_db_transaction() end

204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
      # Appends +LIMIT+ and +OFFSET+ options to an SQL statement, or some SQL
      # fragment that has the same semantics as LIMIT and OFFSET.
      #
      # +options+ must be a Hash which contains a +:limit+ option
      # and an +:offset+ option.
      #
      # This method *modifies* the +sql+ parameter.
      #
      # ===== Examples
      #  add_limit_offset!('SELECT * FROM suppliers', {:limit => 10, :offset => 50})
      # generates
      #  SELECT * FROM suppliers LIMIT 10 OFFSET 50

      def add_limit_offset!(sql, options)
        if limit = options[:limit]
          sql << " LIMIT #{sanitize_limit(limit)}"
        end
        if offset = options[:offset]
          sql << " OFFSET #{offset.to_i}"
        end
        sql
      end

227 228 229 230 231 232 233 234
      def default_sequence_name(table, column)
        nil
      end

      # Set the sequence to the max value of the table's column.
      def reset_sequence!(table, column, sequence = nil)
        # Do nothing by default.  Implement for PostgreSQL, Oracle, ...
      end
235

236
      # Inserts the given fixture into the table. Overridden in adapters that require
237 238
      # something beyond a simple insert (eg. Oracle).
      def insert_fixture(fixture, table_name)
239
        execute "INSERT INTO #{quote_table_name(table_name)} (#{fixture.key_list}) VALUES (#{fixture.value_list})", 'Fixture Insert'
240 241
      end

242 243
      def empty_insert_statement_value
        "VALUES(DEFAULT)"
244 245
      end

246 247 248 249
      def case_sensitive_equality_operator
        "="
      end

250 251 252 253
      def limited_update_conditions(where_sql, quoted_table_name, quoted_primary_key)
        "WHERE #{quoted_primary_key} IN (SELECT #{quoted_primary_key} FROM #{quoted_table_name} #{where_sql})"
      end

254 255 256 257 258
      protected
        # Returns an array of record hashes with the column names as keys and
        # column values as values.
        def select(sql, name = nil)
        end
259
        undef_method :select
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275

        # Returns the last auto-generated ID from the affected table.
        def insert_sql(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil)
          execute(sql, name)
          id_value
        end

        # Executes the update statement and returns the number of rows affected.
        def update_sql(sql, name = nil)
          execute(sql, name)
        end

        # Executes the delete statement and returns the number of rows affected.
        def delete_sql(sql, name = nil)
          update_sql(sql, name)
        end
276 277 278 279 280 281 282 283 284 285 286 287 288 289 290

        # Sanitizes the given LIMIT parameter in order to prevent SQL injection.
        #
        # +limit+ may be anything that can evaluate to a string via #to_s. It
        # should look like an integer, or a comma-delimited list of integers.
        #
        # Returns the sanitized limit parameter, either as an integer, or as a
        # string which contains a comma-delimited list of integers.
        def sanitize_limit(limit)
          if limit.to_s =~ /,/
            limit.to_s.split(',').map{ |i| i.to_i }.join(',')
          else
            limit.to_i
          end
        end
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306

        # Send a rollback message to all records after they have been rolled back. If rollback
        # is false, only rollback records since the last save point.
        def rollback_transaction_records(rollback) #:nodoc
          if rollback
            records = @_current_transaction_records.flatten
            @_current_transaction_records.clear
          else
            records = @_current_transaction_records.pop
          end

          unless records.blank?
            records.uniq.each do |record|
              begin
                record.rolledback!(rollback)
              rescue Exception => e
307
                record.logger.error(e) if record.respond_to?(:logger) && record.logger
308 309 310 311 312 313 314 315 316 317 318 319 320 321
              end
            end
          end
        end

        # Send a commit message to all records after they have been committed.
        def commit_transaction_records #:nodoc
          records = @_current_transaction_records.flatten
          @_current_transaction_records.clear
          unless records.blank?
            records.uniq.each do |record|
              begin
                record.committed!
              rescue Exception => e
322
                record.logger.error(e) if record.respond_to?(:logger) && record.logger
323 324 325 326
              end
            end
          end
        end
327 328
    end
  end
329
end