Are ActiveRecord transactions just 1 round trip to database?

activerecord, rails-activerecord, ruby, ruby-on-rails

Solution

The `ActiveRecord::Base.transaction` call will make two calls to the database:

- One to tell the database to start a transaction.

- And another one when the block exits to tell the database to commit or rollback the transaction.

Each `ActiveRecord::Base.connection.execute` call also talk to the database. This has to happen as the queries that you `execute` might raise exceptions or return useful data. In general, each SQL statement is a separate call (i.e. roundtrip) to the database.

Only one database connection will be used though.

Problem

If I have a bunch of queries that I am executing, wrapped in an Activerecord transaction, are all those queries sent to the database in 1 round trip (ie all queries sent to db, and response sent back), or does each query take up 1 trip each? Example Code: ``` ActiveRecord::Base.transaction do queries.each do |query| ActiveRecord::Base.connection.execute(query) end end ``` If the latter, is there a way to force all the queries inside a transaction to be executed in 1 round trip?

Original source