mercredi 18 avril 2018

Reset ActiveRecord back to default?

Scenario

I have a --mountable Rails engine attached to a parent app. The parent app pulls from a separate data source via its models. With my limited knowledge of Ruby on Rails so far, I used a separate MySQL2 gem connection to load in my engine's data source (not using models thus far in this use case). I know this typically isn't best/standard practice, but I've also got "separate" "pure" Ruby daemons running with the same data source(s), and this solution works for now...

Problem

Except...I've killed the parent app's connection. Upon returning to the parent app (website), it displays ActiveRecord::StatementInvalid in Controller#action ... Mysql2::Error: Table 'foo.bar' doesn't exist: SHOW FULL FIELDS FROM bar.

Possible Solutions(?)

I imagine there's either a way to:

  • Reset the default ActiveRecord connection (reload the ActiveRecord::Base.establish_connection?)
  • If I'm somehow using the same instance as ActiveRecord to create a separate instance to keep my connections separate. In one of my daemons I created a thread pool where each creates and closes its own connection (since one connection can apparently only perform one query at a time), so I know it's possible to call multiple connections at once with this line. But somehow ActiveRecord doesn't play well with this.

Here's my code excerpt from the engine's controller:

def index
  $DBConfig = {host: "blahblah", port: 9999, username: "blahblah", password: "blahblah", database: "blahblah"}
  handler = Mysql2::Client.new($DBConfig)
  data = handler.query("SELECT some FROM data;")
  handler.close
end

I'm also pretty sure I've closed all my existing connections at the ends of all my methods with the handler.close.

Thanks in advance!

Aucun commentaire:

Enregistrer un commentaire