1

I am using golang-migrate to migrate schema. Connection open, migration up and down are working fine. However, db connection is not getting closed, not throwing any error and leave idle connection in database server. My code looks like this:

m, err := migrate.New(sourceURL, "database_connection_string")
defer m.Close()
m.Version()

Has anyone faced similar issue ? How can we address this ?

Original Code

Mayank
  • 5,411
  • 1
  • 16
  • 16
  • Most DB drivers pool idle connections. Are you certain that's not the case here? – JimB Aug 02 '18 at 13:52
  • that is not the case as number of idle connections keep on increasing in database server and when max_connections is reached, servers stops serving further queries. – Mayank Aug 02 '18 at 13:59
  • What happens if you remove defer and put the m.Close after the use of m? – Kenny Grant Aug 02 '18 at 20:16
  • @KennyGrant m.Version() throws error: database/sql connection closed but database server still has listed IDLE connection. How to address that ? – Mayank Aug 03 '18 at 04:46
  • try posting a minimal working example to demonstrate, your original code linked differs from this code a lot. I suspect your defer is the problem, but I mean Close AFTER you have used the conn not before you attempt to use it with m.Version() – Kenny Grant Aug 03 '18 at 06:41

1 Answers1

3

The defer statement will ensure that the m.Close() call is executed after your method returns, so it should not matter where you place the m.Version() call in the method and any attempts to check whether it is closed from within the method will return a false negative.

I have not faced this issue but based on your experience both the Close and Version methods in golang-migrate are suspect. However, that is an open source project, so in your situation I would clone their code, call it from yours, and debug those methods to see what is happening. You will probably find some insights that will help you fix your code, but it is also possible that you find a bug in theirs.