From a4566a399547d7419792233e6e3106da148c84ee Mon Sep 17 00:00:00 2001 From: Brad Lugo Date: Sat, 30 Jul 2022 12:12:32 -0700 Subject: [PATCH] fix!: Unlock doesn't release connection BREAKING CHANGE: Changes the Locker interface and requires the user to call Close instead of Unlock to release the connection. --- README.md | 2 +- go.mod | 2 +- lock.go | 12 +++++++----- lock_test.go | 8 ++++++++ 4 files changed, 17 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 6ec8ea9..4e761e1 100644 --- a/README.md +++ b/README.md @@ -25,7 +25,7 @@ import ( "log" "os" - pglock "github.com/allisson/go-pglock/v2" + "github.com/allisson/go-pglock/v3" _ "github.com/lib/pq" ) diff --git a/go.mod b/go.mod index fb63985..6c898f8 100644 --- a/go.mod +++ b/go.mod @@ -1,4 +1,4 @@ -module github.com/allisson/go-pglock/v2 +module github.com/allisson/go-pglock/v3 go 1.15 diff --git a/lock.go b/lock.go index 951938c..b6494d5 100644 --- a/lock.go +++ b/lock.go @@ -10,6 +10,7 @@ type Locker interface { Lock(ctx context.Context) (bool, error) WaitAndLock(ctx context.Context) error Unlock(ctx context.Context) error + Close() error } // Lock implements the Locker interface. @@ -37,14 +38,15 @@ func (l *Lock) WaitAndLock(ctx context.Context) error { return err } -// Unlock releases the lock and DB connection. +// Unlock releases the lock. func (l *Lock) Unlock(ctx context.Context) error { sqlQuery := "SELECT pg_advisory_unlock($1)" _, err := l.conn.ExecContext(ctx, sqlQuery, l.id) - if err != nil { - return err - } - // Returns the connection to the connection pool + return err +} + +// Close closes the DB connection, consequently releasing all locks. +func (l *Lock) Close() error { return l.conn.Close() } diff --git a/lock_test.go b/lock_test.go index 081570a..b071f56 100644 --- a/lock_test.go +++ b/lock_test.go @@ -47,6 +47,7 @@ func TestNewLock(t *testing.T) { id := int64(10) lock, err := NewLock(context.Background(), id, db) assert.Nil(t, err) + defer assert.Nil(t, lock.Close()) assert.Equal(t, id, lock.id) assert.NotNil(t, lock.conn) } @@ -63,8 +64,10 @@ func TestLockUnlock(t *testing.T) { id := int64(1) lock1, err := NewLock(ctx, id, db1) assert.Nil(t, err) + defer lock1.Close() lock2, err := NewLock(ctx, id, db2) assert.Nil(t, err) + defer lock2.Close() ok, err := lock1.Lock(ctx) assert.True(t, ok) @@ -83,6 +86,9 @@ func TestLockUnlock(t *testing.T) { err = lock2.Unlock(ctx) assert.Nil(t, err) + + err = lock2.Unlock(ctx) + assert.Nil(t, err) } func TestWaitAndLock(t *testing.T) { @@ -98,8 +104,10 @@ func TestWaitAndLock(t *testing.T) { id := int64(1) lock1, err := NewLock(ctx, id, db1) assert.Nil(t, err) + defer lock1.Close() lock2, err := NewLock(ctx, id, db2) assert.Nil(t, err) + defer lock2.Close() start := time.Now() wg.Add(1)