Home > database >  How to simulate "Mysql2::Error: MySQL client is not connected"
How to simulate "Mysql2::Error: MySQL client is not connected"

Time:02-23

Can anyone suggest a way of forcing the above exception to occur, in the context of a Rails app?

I have a particular situation where it arises (involving scheduled database maintenance) and I need to be able to trigger it locally so I can test my application handles it correctly.

I would guess there's either something I could do to the DB itself, or else some method I could call on the ActiveRecord connection that would trigger this, but I haven't been able to figure it out.

CodePudding user response:

You are probably getting this error because the MySQL connection is killed during maintenance while a SQL query is being made. (Here is a test case of this scenario https://github.com/brianmario/mysql2/blob/a8c96fbe277723e53985983415f9875e759e1d47/spec/mysql2/client_spec.rb#L597)

To reproduce this locally, you can run a long running SQL query in rails. E.g.

ActiveRecord::Base.connection.execute("select sleep(100)")

While that is running, find and kill the rails SQL connections by running

 SELECT id FROM INFORMATION_SCHEMA.PROCESSLIST WHERE `db` = '<your-database-name>';
 kill <id>; -- Run for each id listed in the previous query.
  • Related