提交嵌套事务

时间:2017-06-16 20:12:29

标签: ruby-on-rails postgresql activerecord

我们假设我有一种方法可以访问用户范围内的API客户端,API客户端会在用户过期时自动更新用户OAuth令牌。

class User < ActiveRecord::Base

  def api
    ApiClient.new access_token: oauth_access_token,
                  refresh_token: oauth_refresh_token,
                  on_oauth_refresh: -> (tokens) {
                    # This proc will be called by the API client when an 
                    # OAuth refresh occurs
                    update_attributes({
                      oauth_access_token: tokens[:access_token],
                      oauth_refresh_token: tokens[:refresh_token]
                     })
                   }
  end

end

如果我在Rails事务中使用此API并且发生刷新然后发生错误 - 我无法持久保存新的OAuth令牌(因为上面的proc也被视为事务的一部分):

u = User.first

User.transaction { 
  local_info = Info.create!

  # My tokens are expired so the client automatically
  # refreshes them and calls the proc that updates them locally.
  external_info = u.api.get_external_info(local_info.id)

  # Now when I try to locally save the info returned by the API an exception
  # occurs (for example due to validation). This rolls back the entire 
  # transaction (including the update of the user's new tokens.)
  local_info.info = external_info 
  local_info.save!
}

我简化了示例,但基本上消耗API和API返回的数据持久性需要在事务中发生。即使父事务失败,我如何确保提交用户的令牌更新。

3 个答案:

答案 0 :(得分:2)

您是否尝试在新线程中打开新的数据库连接,并在此线程中执行更新

u = User.first

User.transaction { 
   local_info = Info.create!

   # My tokens are expired so the client automatically
   # refreshes them and calls the proc that updates them locally.
   external_info = u.api.get_external_info(local_info.id)

   # Now when I try to locally save the info returned by the API an exception
   # occurs (for example due to validation). This rolls back the entire 
   # transaction (including the update of the user's new tokens.)
   local_info.info = external_info 
   local_info.save!

   # Now open new thread
   # In the new thread open new db connection, separate from the one already opened
   # In the new connection execute update only for the tokens
   # Close new connection and new thread
   Thread.new do
      ActiveRecord::Base.connection_pool.with_connection do |connection|
         connection.execute("Your SQL statement that will update the user tokens")        
      end
   end.join
}

我希望这会有所帮助

答案 1 :(得分:0)

上一个问题中的discussion可能会对您有所帮助。看起来您可以设置requires_new: true标志,并将子事务标记为子事务。

User.transaction { 
  User.transaction(requires_new: true) { 
    u.update_attribute(:name, 'test') 
  }; 

  u.update_attribute(:name, 'test2'); 

  raise 'boom' 
}

答案 2 :(得分:0)

Nermin(接受的)答案是正确的。这是Rails> = 5.0

的更新
Thread.new do
  Rails.application.executor.wrap do
    record.save
  end
  # Note: record probably won't be updated here yet since it's async
end

此处记录:Rails guides threading and concurrency