Manual instantiation of ActiveRecord Connection Pool results in garbled data

Hi there everyone,

I’m new to these forum, not so new to Rails but when I come across instances like this it sure feels like it. Perhaps some wiser eyes might shed some light on the puzzling situation.

For a project we created a database connection manually via ActiveRecord due to the manner in which we retrieve the connection details. I’ll start off by explaining the result of the effect:

  • Reading from the database using raw sql results in jumbled data at times, others only column names inserted in the field values and at other the correct type of data but clearly associated with a different request

Below is the code used to create the Connection, done as a ||= singleton and the connection details read into :database1. I’m interested in understanding the problem more than the solution, but a solution would be quite nice too.

class DataSources
    def self.database1
        @database1 ||= ActiveRecord::Base.establish_connection(:database1).connection
        @database1.reconnect! unless

From what I understood going through the docs this should create a connection pool and automatically handle the threading and pooling.

When using the connection I simply called the connection pool:

query_result = DataSources.exec_query("<some raw sql>")


query_result = DataSources.query("<some raw sql>")

My immediate thought was that this is the same connection being read by different calls, a form of a race condition, as it only happened when multiple requests happened in the same short span of time close enough together.

A fellow developer thinks the issue might be “due to the ||=” but I don’t understand how that could be the case, and we don’t want to create a new connection pool each time a query needs to be processed and set up n number of connections to the database.