diff options
author | Pratik Naik <pratiknaik@gmail.com> | 2009-01-14 15:36:27 +0000 |
---|---|---|
committer | Pratik Naik <pratiknaik@gmail.com> | 2009-01-14 15:36:27 +0000 |
commit | deb597d63db0c903ce0ff70ab53abed60f95192a (patch) | |
tree | 52cd072f2e666baa0286aea741c365d7cb30f42f /activerecord | |
parent | e46c80765525817a89b784e6336a9f66250d53fc (diff) | |
parent | 9bcf01b23c25e640da7908ac8b1b49fbf7d2e51a (diff) | |
download | rails-deb597d63db0c903ce0ff70ab53abed60f95192a.tar.gz rails-deb597d63db0c903ce0ff70ab53abed60f95192a.tar.bz2 rails-deb597d63db0c903ce0ff70ab53abed60f95192a.zip |
Merge commit 'mainstream/master'
Diffstat (limited to 'activerecord')
11 files changed, 421 insertions, 87 deletions
diff --git a/activerecord/CHANGELOG b/activerecord/CHANGELOG index 2bde8d402b..fbc71cddf1 100644 --- a/activerecord/CHANGELOG +++ b/activerecord/CHANGELOG @@ -1,5 +1,7 @@ *2.3.0/3.0* +* Support nested transactions using database savepoints. #383 [Jonathan Viney, Hongli Lai] + * Added dynamic scopes ala dynamic finders #1648 [Yaroslav Markin] * Fixed that ActiveRecord::Base#new_record? should return false (not nil) for existing records #1219 [Yaroslav Markin] diff --git a/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb b/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb index 189c6c7b5a..08601da00a 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb @@ -53,36 +53,124 @@ module ActiveRecord def delete(sql, name = nil) delete_sql(sql, name) end + + # 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 + + # 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. + # - However, if +:requires_new+ is set, the block will be wrapped in a + # database savepoint acting as a sub-transaction. + # + # === 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 + # Model.connection.transaction(:requires_new => true) do # CREATE SAVEPOINT active_record_1 + # Model.connection.create_table(...) + # # active_record_1 now automatically released + # end # RELEASE SAVEPOINT active_record_1 <--- BOOM! database error! + # end + def transaction(options = {}) + options.assert_valid_keys :requires_new, :joinable + + last_transaction_joinable = @transaction_joinable + if options.has_key?(:joinable) + @transaction_joinable = options[:joinable] + else + @transaction_joinable = true + end + requires_new = options[:requires_new] || !last_transaction_joinable - # Wrap a block in a transaction. Returns result of block. - def transaction(start_db_transaction = true) transaction_open = false begin if block_given? - if start_db_transaction - begin_db_transaction + if requires_new || open_transactions == 0 + if open_transactions == 0 + begin_db_transaction + elsif requires_new + create_savepoint + end + increment_open_transactions transaction_open = true end yield end rescue Exception => database_transaction_rollback - if transaction_open + if transaction_open && !outside_transaction? transaction_open = false - rollback_db_transaction + decrement_open_transactions + if open_transactions == 0 + rollback_db_transaction + else + rollback_to_savepoint + end end - raise unless database_transaction_rollback.is_a? ActiveRecord::Rollback + raise unless database_transaction_rollback.is_a?(ActiveRecord::Rollback) end ensure - if transaction_open + @transaction_joinable = last_transaction_joinable + + if outside_transaction? + @open_transactions = 0 + elsif transaction_open + decrement_open_transactions begin - commit_db_transaction + if open_transactions == 0 + commit_db_transaction + else + release_savepoint + end rescue Exception => database_transaction_rollback - rollback_db_transaction + if open_transactions == 0 + rollback_db_transaction + else + rollback_to_savepoint + end raise end end end - + # Begins the transaction (and turns off auto-committing). def begin_db_transaction() end diff --git a/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb b/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb index bfafcfb3ab..a8cd9f033b 100755 --- a/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb @@ -66,6 +66,12 @@ module ActiveRecord def supports_ddl_transactions? false end + + # Does this adapter support savepoints? PostgreSQL and MySQL do, SQLite + # does not. + def supports_savepoints? + false + end # Should primary key values be selected from their corresponding # sequence before the insert statement? If true, next_sequence_value @@ -160,6 +166,23 @@ module ActiveRecord @open_transactions -= 1 end + def transaction_joinable=(joinable) + @transaction_joinable = joinable + end + + def create_savepoint + end + + def rollback_to_savepoint + end + + def release_savepoint + end + + def current_savepoint_name + "active_record_#{open_transactions}" + end + def log_info(sql, name, ms) if @logger && @logger.debug? name = '%s (%.1fms)' % [name || 'SQL', ms] diff --git a/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb b/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb index 60729c63db..b2345fd571 100644 --- a/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb @@ -210,6 +210,10 @@ module ActiveRecord def supports_migrations? #:nodoc: true end + + def supports_savepoints? #:nodoc: + true + end def native_database_types #:nodoc: NATIVE_DATABASE_TYPES @@ -349,6 +353,17 @@ module ActiveRecord # Transactions aren't supported end + def create_savepoint + execute("SAVEPOINT #{current_savepoint_name}") + end + + def rollback_to_savepoint + execute("ROLLBACK TO SAVEPOINT #{current_savepoint_name}") + end + + def release_savepoint + execute("RELEASE SAVEPOINT #{current_savepoint_name}") + end def add_limit_offset!(sql, options) #:nodoc: if limit = options[:limit] diff --git a/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb b/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb index 6685cb8663..913bb521ca 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb @@ -272,6 +272,10 @@ module ActiveRecord def supports_ddl_transactions? true end + + def supports_savepoints? + true + end # Returns the configured supported identifier length supported by PostgreSQL, # or report the default of 63 on PostgreSQL 7.x. @@ -528,45 +532,26 @@ module ActiveRecord def rollback_db_transaction execute "ROLLBACK" end + + if defined?(PGconn::PQTRANS_IDLE) + # The ruby-pg driver supports inspecting the transaction status, + # while the ruby-postgres driver does not. + def outside_transaction? + @connection.transaction_status == PGconn::PQTRANS_IDLE + end + end - # ruby-pg defines Ruby constants for transaction status, - # ruby-postgres does not. - PQTRANS_IDLE = defined?(PGconn::PQTRANS_IDLE) ? PGconn::PQTRANS_IDLE : 0 - - # Check whether a transaction is active. - def transaction_active? - @connection.transaction_status != PQTRANS_IDLE + def create_savepoint + execute("SAVEPOINT #{current_savepoint_name}") end - # Wrap a block in a transaction. Returns result of block. - def transaction(start_db_transaction = true) - transaction_open = false - begin - if block_given? - if start_db_transaction - begin_db_transaction - transaction_open = true - end - yield - end - rescue Exception => database_transaction_rollback - if transaction_open && transaction_active? - transaction_open = false - rollback_db_transaction - end - raise unless database_transaction_rollback.is_a? ActiveRecord::Rollback - end - ensure - if transaction_open && transaction_active? - begin - commit_db_transaction - rescue Exception => database_transaction_rollback - rollback_db_transaction - raise - end - end + def rollback_to_savepoint + execute("ROLLBACK TO SAVEPOINT #{current_savepoint_name}") end + def release_savepoint + execute("RELEASE SAVEPOINT #{current_savepoint_name}") + end # SCHEMA STATEMENTS ======================================== diff --git a/activerecord/lib/active_record/fixtures.rb b/activerecord/lib/active_record/fixtures.rb index 129306d335..0131d9fac5 100644 --- a/activerecord/lib/active_record/fixtures.rb +++ b/activerecord/lib/active_record/fixtures.rb @@ -516,7 +516,7 @@ class Fixtures < (RUBY_VERSION < '1.9' ? YAML::Omap : Hash) all_loaded_fixtures.update(fixtures_map) - connection.transaction(connection.open_transactions.zero?) do + connection.transaction(:requires_new => true) do fixtures.reverse.each { |fixture| fixture.delete_existing_fixtures } fixtures.each { |fixture| fixture.insert_fixtures } @@ -937,6 +937,7 @@ module ActiveRecord @@already_loaded_fixtures[self.class] = @loaded_fixtures end ActiveRecord::Base.connection.increment_open_transactions + ActiveRecord::Base.connection.transaction_joinable = false ActiveRecord::Base.connection.begin_db_transaction # Load fixtures for every test. else diff --git a/activerecord/lib/active_record/session_store.rb b/activerecord/lib/active_record/session_store.rb index bd198c03b2..5e45cf65ab 100644 --- a/activerecord/lib/active_record/session_store.rb +++ b/activerecord/lib/active_record/session_store.rb @@ -53,11 +53,6 @@ module ActiveRecord before_save :raise_on_session_data_overflow! class << self - # Don't try to reload ARStore::Session in dev mode. - def reloadable? #:nodoc: - false - end - def data_column_size_limit @data_column_size_limit ||= columns_hash[@@data_column_name].limit end diff --git a/activerecord/lib/active_record/transactions.rb b/activerecord/lib/active_record/transactions.rb index 0a27ea980e..0b6e52c79b 100644 --- a/activerecord/lib/active_record/transactions.rb +++ b/activerecord/lib/active_record/transactions.rb @@ -120,16 +120,66 @@ module ActiveRecord # end # # One should restart the entire transaction if a StatementError occurred. + # + # == Nested transactions + # + # #transaction calls can be nested. By default, this makes all database + # statements in the nested transaction block become part of the parent + # transaction. For example: + # + # User.transaction do + # User.create(:username => 'Kotori') + # User.transaction do + # User.create(:username => 'Nemu') + # raise ActiveRecord::Rollback + # end + # end + # + # User.find(:all) # => empty + # + # It is also possible to requires a sub-transaction by passing + # <tt>:requires_new => true</tt>. If anything goes wrong, the + # database rolls back to the beginning of the sub-transaction + # without rolling back the parent transaction. For example: + # + # User.transaction do + # User.create(:username => 'Kotori') + # User.transaction(:requires_new => true) do + # User.create(:username => 'Nemu') + # raise ActiveRecord::Rollback + # end + # end + # + # User.find(:all) # => Returns only Kotori + # + # Most databases don't support true nested transactions. At the time of + # writing, the only database that we're aware of that supports true nested + # transactions, is MS-SQL. Because of this, Active Record emulates nested + # transactions by using savepoints. See + # http://dev.mysql.com/doc/refman/5.0/en/savepoints.html + # for more information about savepoints. + # + # === Caveats + # + # If you're on MySQL, then do not use DDL operations in nested transactions + # blocks that are emulated with savepoints. That is, do not execute statements + # like 'CREATE TABLE' inside such blocks. This is because MySQL automatically + # releases all savepoints upon executing a DDL operation. When #transaction + # is finished and tries to release the savepoint it created earlier, a + # database error will occur because the savepoint has already been + # automatically released. The following example demonstrates the problem: + # + # Model.connection.transaction do # BEGIN + # Model.connection.transaction(:requires_new => true) do # CREATE SAVEPOINT active_record_1 + # Model.connection.create_table(...) # active_record_1 now automatically released + # end # RELEASE savepoint active_record_1 + # # ^^^^ BOOM! database error! + # end module ClassMethods # See ActiveRecord::Transactions::ClassMethods for detailed documentation. - def transaction(&block) - connection.increment_open_transactions - - begin - connection.transaction(connection.open_transactions == 1, &block) - ensure - connection.decrement_open_transactions - end + def transaction(options = {}, &block) + # See the ConnectionAdapters::DatabaseStatements#transaction API docs. + connection.transaction(options, &block) end end diff --git a/activerecord/test/cases/defaults_test.rb b/activerecord/test/cases/defaults_test.rb index 38e4853dc0..b4032c23e6 100644 --- a/activerecord/test/cases/defaults_test.rb +++ b/activerecord/test/cases/defaults_test.rb @@ -18,11 +18,43 @@ class DefaultTest < ActiveRecord::TestCase end end - if current_adapter?(:MysqlAdapter) + if current_adapter?(:PostgreSQLAdapter, :FirebirdAdapter, :OpenBaseAdapter, :OracleAdapter) + def test_default_integers + default = Default.new + assert_instance_of Fixnum, default.positive_integer + assert_equal 1, default.positive_integer + assert_instance_of Fixnum, default.negative_integer + assert_equal -1, default.negative_integer + assert_instance_of BigDecimal, default.decimal_number + assert_equal BigDecimal.new("2.78"), default.decimal_number + end + end + + if current_adapter?(:PostgreSQLAdapter) + def test_multiline_default_text + # older postgres versions represent the default with escapes ("\\012" for a newline) + assert ( "--- []\n\n" == Default.columns_hash['multiline_default'].default || + "--- []\\012\\012" == Default.columns_hash['multiline_default'].default) + end + end +end - #MySQL 5 and higher is quirky with not null text/blob columns. - #With MySQL Text/blob columns cannot have defaults. If the column is not null MySQL will report that the column has a null default - #but it behaves as though the column had a default of '' +if current_adapter?(:MysqlAdapter) + class DefaultsTestWithoutTransactionalFixtures < ActiveRecord::TestCase + # ActiveRecord::Base#create! (and #save and other related methods) will + # open a new transaction. When in transactional fixtures mode, this will + # cause ActiveRecord to create a new savepoint. However, since MySQL doesn't + # support DDL transactions, creating a table will result in any created + # savepoints to be automatically released. This in turn causes the savepoint + # release code in AbstractAdapter#transaction to fail. + # + # We don't want that to happen, so we disable transactional fixtures here. + self.use_transactional_fixtures = false + + # MySQL 5 and higher is quirky with not null text/blob columns. + # With MySQL Text/blob columns cannot have defaults. If the column is not + # null MySQL will report that the column has a null default + # but it behaves as though the column had a default of '' def test_mysql_text_not_null_defaults klass = Class.new(ActiveRecord::Base) klass.table_name = 'test_mysql_text_not_null_defaults' @@ -48,8 +80,7 @@ class DefaultTest < ActiveRecord::TestCase ensure klass.connection.drop_table(klass.table_name) rescue nil end - - + # MySQL uses an implicit default 0 rather than NULL unless in strict mode. # We use an implicit NULL so schema.rb is compatible with other databases. def test_mysql_integer_not_null_defaults @@ -77,24 +108,4 @@ class DefaultTest < ActiveRecord::TestCase klass.connection.drop_table(klass.table_name) rescue nil end end - - if current_adapter?(:PostgreSQLAdapter, :FirebirdAdapter, :OpenBaseAdapter, :OracleAdapter) - def test_default_integers - default = Default.new - assert_instance_of Fixnum, default.positive_integer - assert_equal 1, default.positive_integer - assert_instance_of Fixnum, default.negative_integer - assert_equal -1, default.negative_integer - assert_instance_of BigDecimal, default.decimal_number - assert_equal BigDecimal.new("2.78"), default.decimal_number - end - end - - if current_adapter?(:PostgreSQLAdapter) - def test_multiline_default_text - # older postgres versions represent the default with escapes ("\\012" for a newline) - assert ( "--- []\n\n" == Default.columns_hash['multiline_default'].default || - "--- []\\012\\012" == Default.columns_hash['multiline_default'].default) - end - end end diff --git a/activerecord/test/cases/helper.rb b/activerecord/test/cases/helper.rb index 2043138ca3..ccd04b67f6 100644 --- a/activerecord/test/cases/helper.rb +++ b/activerecord/test/cases/helper.rb @@ -34,7 +34,7 @@ rescue LoadError end ActiveRecord::Base.connection.class.class_eval do - IGNORED_SQL = [/^PRAGMA/, /^SELECT currval/, /^SELECT CAST/, /^SELECT @@IDENTITY/, /^SELECT @@ROWCOUNT/] + IGNORED_SQL = [/^PRAGMA/, /^SELECT currval/, /^SELECT CAST/, /^SELECT @@IDENTITY/, /^SELECT @@ROWCOUNT/, /^SAVEPOINT/, /^ROLLBACK TO SAVEPOINT/, /^RELEASE SAVEPOINT/] def execute_with_query_record(sql, name = nil, &block) $queries_executed ||= [] diff --git a/activerecord/test/cases/transactions_test.rb b/activerecord/test/cases/transactions_test.rb index b12ec36455..4a07a8bb1d 100644 --- a/activerecord/test/cases/transactions_test.rb +++ b/activerecord/test/cases/transactions_test.rb @@ -213,11 +213,104 @@ class TransactionTest < ActiveRecord::TestCase assert Topic.find(2).approved?, "Second should still be approved" end + def test_invalid_keys_for_transaction + assert_raises ArgumentError do + Topic.transaction :nested => true do + end + end + end + + def test_force_savepoint_in_nested_transaction + Topic.transaction do + @first.approved = true + @second.approved = false + @first.save! + @second.save! + + begin + Topic.transaction :requires_new => true do + @first.happy = false + @first.save! + raise + end + rescue + end + end + + assert @first.reload.approved? + assert !@second.reload.approved? + end if Topic.connection.supports_savepoints? + + def test_no_savepoint_in_nested_transaction_without_force + Topic.transaction do + @first.approved = true + @second.approved = false + @first.save! + @second.save! + + begin + Topic.transaction do + @first.approved = false + @first.save! + raise + end + rescue + end + end + + assert !@first.reload.approved? + assert !@second.reload.approved? + end if Topic.connection.supports_savepoints? + + def test_many_savepoints + Topic.transaction do + @first.content = "One" + @first.save! + + begin + Topic.transaction :requires_new => true do + @first.content = "Two" + @first.save! + + begin + Topic.transaction :requires_new => true do + @first.content = "Three" + @first.save! + + begin + Topic.transaction :requires_new => true do + @first.content = "Four" + @first.save! + raise + end + rescue + end + + @three = @first.reload.content + raise + end + rescue + end + + @two = @first.reload.content + raise + end + rescue + end + + @one = @first.reload.content + end + + assert_equal "One", @one + assert_equal "Two", @two + assert_equal "Three", @three + end if Topic.connection.supports_savepoints? + uses_mocha 'mocking connection.commit_db_transaction' do def test_rollback_when_commit_raises Topic.connection.expects(:begin_db_transaction) - Topic.connection.expects(:transaction_active?).returns(true) if current_adapter?(:PostgreSQLAdapter) Topic.connection.expects(:commit_db_transaction).raises('OH NOES') + Topic.connection.expects(:outside_transaction?).returns(false) Topic.connection.expects(:rollback_db_transaction) assert_raise RuntimeError do @@ -227,6 +320,38 @@ class TransactionTest < ActiveRecord::TestCase end end end + + if current_adapter?(:PostgreSQLAdapter) && defined?(PGconn::PQTRANS_IDLE) + def test_outside_transaction_works + assert Topic.connection.outside_transaction? + Topic.connection.begin_db_transaction + assert !Topic.connection.outside_transaction? + Topic.connection.rollback_db_transaction + assert Topic.connection.outside_transaction? + end + + uses_mocha 'mocking connection.rollback_db_transaction' do + def test_rollback_wont_be_executed_if_no_transaction_active + assert_raise RuntimeError do + Topic.transaction do + Topic.connection.rollback_db_transaction + Topic.connection.expects(:rollback_db_transaction).never + raise "Rails doesn't scale!" + end + end + end + end + + def test_open_transactions_count_is_reset_to_zero_if_no_transaction_active + Topic.transaction do + Topic.transaction do + Topic.connection.rollback_db_transaction + end + assert_equal 0, Topic.connection.open_transactions + end + assert_equal 0, Topic.connection.open_transactions + end + end def test_sqlite_add_column_in_transaction_raises_statement_invalid return true unless current_adapter?(:SQLite3Adapter, :SQLiteAdapter) @@ -282,6 +407,45 @@ class TransactionTest < ActiveRecord::TestCase end end +class TransactionsWithTransactionalFixturesTest < ActiveRecord::TestCase + self.use_transactional_fixtures = true + fixtures :topics + + def test_automatic_savepoint_in_outer_transaction + @first = Topic.find(1) + + begin + Topic.transaction do + @first.approved = true + @first.save! + raise + end + rescue + assert !@first.reload.approved? + end + end + + def test_no_automatic_savepoint_for_inner_transaction + @first = Topic.find(1) + + Topic.transaction do + @first.approved = true + @first.save! + + begin + Topic.transaction do + @first.approved = false + @first.save! + raise + end + rescue + end + end + + assert !@first.reload.approved? + end +end if Topic.connection.supports_savepoints? + if current_adapter?(:PostgreSQLAdapter) class ConcurrentTransactionTest < TransactionTest use_concurrent_connections |