Skip to content

Commit

Permalink
Merge pull request #60 from olachat/yinloo/fix-lock
Browse files Browse the repository at this point in the history
log and return error if dbConn.Close() fails
  • Loading branch information
yinloo-ola authored Mar 13, 2024
2 parents e44a3a0 + 177ca65 commit 16391ff
Showing 1 changed file with 11 additions and 5 deletions.
16 changes: 11 additions & 5 deletions coredb/tx.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"database/sql"
"errors"
"fmt"
"log"
)

// BeginTx returns a custom db.Tx based on opts. This method exists for flexibility.
Expand Down Expand Up @@ -205,17 +206,22 @@ func (t *TxProvider) Tx(ctx context.Context, fn func(TxContext) error) error {
return t.TxWithOpts(ctx, fn, nil, &DefaultTxOpts)
}

func (t *TxProvider) TxWithLock(ctx context.Context, lock string, durationInSec int, fn func(txContext TxContext) error) error {
// TxWithLock executes a transaction with a lock and a specified duration in seconds.
func (t *TxProvider) TxWithLock(ctx context.Context, lock string, durationInSec int, fn func(txContext TxContext) error) (err error) {
connCtx, cancel := context.WithCancel(context.Background())
dbConn, err := t.conn.Conn(connCtx)
dbConn, errConn := t.conn.Conn(connCtx)
defer func() {
cancel()
if dbConn != nil {
dbConn.Close()
errCloseConn := dbConn.Close()
if errCloseConn != nil {
log.Printf("fail to close db connection: %#v", errCloseConn)
err = errCloseConn
}
}
}()
if err != nil {
return fmt.Errorf("fail to get db connection: %w", err)
if errConn != nil {
return fmt.Errorf("fail to get db connection: %w", errConn)
}

{
Expand Down

0 comments on commit 16391ff

Please sign in to comment.