DATA-DOG / go-sqlmock

Sql mock driver for golang to test database interactions
Other
6.16k stars 407 forks source link

Cannot open connection after all connections closed #250

Closed ianlewis closed 3 years ago

ianlewis commented 3 years ago

sqlmock deletes the dsn from the connections if all connections for that dsn have been closed.

https://github.com/DATA-DOG/go-sqlmock/blob/f920cc853bd3163842d5da3b46271eb274273b6f/sqlmock.go#L149-L151

and then returns an error if the given dsn is not in the connections list.

https://github.com/DATA-DOG/go-sqlmock/blob/f920cc853bd3163842d5da3b46271eb274273b6f/sqlmock.go#L149-L151

Sqlmock should allow new connections be be created even after all connections have been closed.

Consider the following code. cancel() when used with transactions causes the sql package to close and discard the connection. On the second call to withCancel the sql package with try to create a new connection but will fail because all connections have been closed.


func withCancel(db *sql.DB) {
    ctx, cancel := context.WithCancel(context.Background())
    tx, _ := db.BeginTx()
    defer cancel()

    // ...
}

func TestWithCancel() {
  db, _, _ := sqlmock.New()
  withCancel(db)
  withCancel(db)
}

A workaround is to use NewWithDSN using your own dsn and always make sure that you have one more connection open than you need to that it's not deleted from the connections list.

l3pp4rd commented 3 years ago

Hi, maybe you could open a pull request fixing the issue, if you have some time to spare?

ianlewis commented 3 years ago

I'll close this since I couldn't reproduce it. It might have been the result of the behavior of a specific version of the go sql package.