Title: Check for active connections to postgres before truncating all databases to avoid TRDeadlock
Tags: ruby;postgresql;sequel;database-deadlocks;database-cleaner
Question: We have an API automation suite where multiple services are running in docker along with the postgres database. We truncate the databases before each test by using the database-cleaner gem. The suite is written in Ruby. We have around 300 cucumber scenarios running and we are noticing a TRDeadlock error on some scenarios. This is thrown when truncating the database and is making the tests flaky.
I want to wait for all active connections to close before I truncate the databases. Is there a way I can do this in Ruby? Here is the script that resets the db. There are 6 dbs in total but I am adding one as an example:
require 'database_cleaner'
require 'database_cleaner/sequel'
require 'sequel'
db_logger = Logger.new(STDOUT, level: Logger75b5:f2c1:f5d7:b954:8dc3:cee9:baf:a8c0WARN)
DB_HOST = ENV['DB_HOST']
DB_1 = Sequel.connect(&quot;postgres://postgres:postgres@#{DB_HOST}:5432/db1&quot;, logger: db_logger)
DatabaseCleaner[:sequel].strategy = [:truncation, except: [&quot;databasechangelog&quot;]]
def clean_dbs
logger.info('## Cleaning all databases...')
DatabaseCleaner[:sequel].db = DB_1
DatabaseCleaner[:sequel].clean
logger.info('## All databases truncated')
Where can I add the check for active connections before truncating? Or is there a different solution to avoid the TRDeadlock?
Please help



{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 0, 'CommentCount': 0, 'ContentLicense': 'CC BY-SA 4.0', 'CreationDate': '2022:00:03/10/22', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<ruby><postgresql><sequel><database-deadlocks><database-cleaner>', 'Title': 'Check for active connections to postgres before truncating all databases to avoid TRDeadlock', 'ViewCount': 10, 'id': 71425825, 'user_AboutMe': '<p>Tech Enthusiast | Fast Learner | Challenger | Problem Solver | Automation &amp; Orchestration</p>\n\n<p>I have worked with different types of testing challenges and have always come out stronger and more aware of things. I love taking up challenges. For me failure is a learning and the real failure is giving up. Learning complete pipelining right now including tests like API testing, End to End testing, performance testing and load testing. Next challenge is to use the testing data to draw information that can further assist in testing.</p>\n', 'user_AccountId': 17099057.0, 'user_DisplayName': 'Sankalan Parajuli', 'user_Reputation': 654.0, 'user_Views': 59.0, 'user_id': 12373410.0}}