1

How to manage opening and closing database connections while working with activerecords and multiple threads asks about how to handle multiple threads with their own connection, each.

I wish to do something similar, but not the same: within my single (default/main) thread in a Rails application (Rails 4 if it matters, and it cannot be upgraded to Rails 5 for this issue), I wish to execute some ActiveRecord code on a separate connection from the main one.

I.e. (rough pseudo code):

MyModel.find(...)....      # works on the normal, basic connection handled by "the system"

conn = ActiveRecord::...   # separate connection only used here
MyModel.find(...)          # original connection
MyModel.create!(..., use_connection: conn) # separate connection only used here
MyModel.find(...)          # original connection
some_obj.do_something(...) # original connection
conn.close                 # separate connection only used here

MyModel.find(...)          # original connection

Questions:

  • I am aware of establish_connectionetc., but those methods seem to assume that there is one connection; i.e. they automatically close/replace the original one, or at least it seems so after glancing through the APIs. What's the correct way to just create a new connection and not have it influence any existing one?
  • Addendum: doing a temporary replacement of the default connection is not possible; other code like some_obj.do_something should use the original connection even when working with MyModel, in the example.
  • How do I tell AR to actually use the new connection for that specific line? Usually, one would have a separate connection on a model-by-model case, but here I wish to have a purely temporary connection completely unrelated to any specific model.

N.B.: Please do note that I know what I'm doing on the DB level, i.e. I know how all the transaction stuff works, and am *not* looking for ActiveRecord::Base#transaction. I am also not just looking for ways of fooling AR's commit handling or something like that. I am aware of transactional and performance issues surrounding this, and the code example given above is obviously not the real code or even close to it (needs exception handling etc.). Please don't answer with an X-Y-problem solution. Think 'autonomous transaction' in Oracle-speak.

AnoE
  • 8,048
  • 1
  • 21
  • 36
  • `establish_connection` assumes one connection _per Model_. I worked with two identical DB simultaneously and I had to use 2 Models with own establish_connection _per entity_. – Pavel Mikhailyuk Apr 30 '18 at 13:22
  • @PavelMikhailyuk, thanks for mentioning that - that is the "solution" (hack) I wish to replace. It is fine (well, ugly but working) for one or two dedicated models, but in general it is not applicable. – AnoE Apr 30 '18 at 15:53

0 Answers0