From db609c2b69f9af7a6037b449e5b3cf5c73aedd33 Mon Sep 17 00:00:00 2001 From: Jia Hui Lee Date: Tue, 19 Mar 2024 10:57:49 +0800 Subject: [PATCH] add comment and also refactoring for dbConn.Close() --- locker_client.go | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/locker_client.go b/locker_client.go index fece8e4..2e8168a 100644 --- a/locker_client.go +++ b/locker_client.go @@ -66,9 +66,9 @@ func (l MysqlLocker) ObtainTimeoutContext(ctx context.Context, key string, timeo var res sql.NullInt32 err = row.Scan(&res) - if err != nil || !res.Valid || res.Int32 != int32(1) { + if err != nil { + //Close database connection whenever failed to acquire lock defer dbConn.Close() - // mysql error does not tell if it was due to context closing, checking it manually select { case <-ctx.Done(): @@ -80,11 +80,15 @@ func (l MysqlLocker) ObtainTimeoutContext(ctx context.Context, key string, timeo cancelFunc() return nil, fmt.Errorf("could not read mysql response: %w", err) } else if !res.Valid { + //Close database connection whenever failed to acquire lock + defer dbConn.Close() // Internal MySQL error occurred, such as out-of-memory, thread killed or others (the doc is not clear) // Note: some MySQL/MariaDB versions (like MariaDB 10.1) does not support -1 as timeout parameters cancelFunc() return nil, ErrMySQLInternalError } else if res.Int32 == 0 { + //Close database connection whenever failed to acquire lock + defer dbConn.Close() // MySQL Timeout cancelFunc() return nil, ErrMySQLTimeout