@@ -115,9 +115,15 @@ func (h *handler) NewConnection(c *mysql.Conn) {
115
115
116
116
func (h * handler ) ConnectionClosed (c * mysql.Conn ) {
117
117
h .Logger .Info ("Connection closed" , "connectionID" , c .ConnectionID , "username" , c .User )
118
-
118
+ // You might be tempted to just have a top lock and just defer the unlock
119
+ //
120
+ // However, it's not working for some reasons when two connections are created at the same time
121
+ // (probably related to a global database/sql variable because test clients and the test server are using sql.register)
122
+ // Also, because conn.Close() can take some time, we don't want to block the other goroutines.
123
+ h .mutexConnectionMapperSQLite .Lock ()
119
124
// Close the connection associated with the MySQL connection
120
125
if conn , ok := h .connectionMapperSQLite [c .ConnectionID ]; ok {
126
+ h .mutexConnectionMapperSQLite .Unlock ()
121
127
// Return the connection to the pool
122
128
err := conn .Close ()
123
129
if err != nil {
@@ -127,7 +133,9 @@ func (h *handler) ConnectionClosed(c *mysql.Conn) {
127
133
h .mutexConnectionMapperSQLite .Lock ()
128
134
delete (h .connectionMapperSQLite , c .ConnectionID )
129
135
h .mutexConnectionMapperSQLite .Unlock ()
136
+
130
137
} else {
138
+ h .mutexConnectionMapperSQLite .Unlock ()
131
139
h .Logger .Error ("SQLite connection not found" , "connectionID" , c .ConnectionID , "username" , c .User )
132
140
}
133
141
@@ -249,7 +257,9 @@ func (h *handler) runSimpleQuery(connectionID uint32, query string, args ...any)
249
257
h .Logger .Debug ("Running query: " , "query" , query )
250
258
251
259
// Retrieve the connection associated with the MySQL connection
260
+ h .mutexConnectionMapperSQLite .Lock () // To ensure we don't read during a write
252
261
conn , ok := h .connectionMapperSQLite [connectionID ]
262
+ h .mutexConnectionMapperSQLite .Unlock ()
253
263
if ! ok {
254
264
h .Logger .Error ("SQLite connection not found" , "connectionID" , connectionID )
255
265
return nil , fmt .Errorf ("SQLite connection not found" )
0 commit comments