/
locks.go
69 lines (61 loc) · 2.01 KB
/
locks.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package storage
import (
"context"
"errors"
"fmt"
"github.com/go-pg/pg/v10"
)
var ErrLockNotAcquired = errors.New("lock not acquired")
var ErrLockNotReleased = errors.New("lock not released")
// An AdvisoryLock is a lock that is managed by Postgres but is only enforced by the application. Advisory
// locks are automatically released at the end of a session. It is safe to hold both a shared and exclusive
// lock within a single session.
type AdvisoryLock int64
// LockShared tries to acquire a session scoped exclusive advisory lock.
func (l AdvisoryLock) LockExclusive(ctx context.Context, db *pg.DB) error {
var acquired bool
_, err := db.QueryOneContext(ctx, pg.Scan(&acquired), `SELECT pg_try_advisory_lock(?);`, int64(l))
if err != nil {
return fmt.Errorf("acquiring exclusive lock: %w", err)
}
if !acquired {
return ErrLockNotAcquired
}
return nil
}
// UnlockExclusive releases an exclusive advisory lock.
func (l AdvisoryLock) UnlockExclusive(ctx context.Context, db *pg.DB) error {
var released bool
_, err := db.QueryOneContext(ctx, pg.Scan(&released), `SELECT pg_advisory_unlock(?);`, int64(l))
if err != nil {
return fmt.Errorf("unlocking exclusive lock: %w", err)
}
if !released {
return ErrLockNotReleased
}
return nil
}
// LockShared tries to acquire a session scoped shared advisory lock.
func (l AdvisoryLock) LockShared(ctx context.Context, db *pg.DB) error {
var acquired bool
_, err := db.QueryOneContext(ctx, pg.Scan(&acquired), `SELECT pg_try_advisory_lock_shared(?);`, int64(l))
if err != nil {
return fmt.Errorf("acquiring exclusive lock: %w", err)
}
if !acquired {
return ErrLockNotAcquired
}
return nil
}
// UnlockShared releases a shared advisory lock.
func (l AdvisoryLock) UnlockShared(ctx context.Context, db *pg.DB) error {
var released bool
_, err := db.QueryOneContext(ctx, pg.Scan(&released), `SELECT pg_advisory_unlock_shared(?);`, int64(l))
if err != nil {
return fmt.Errorf("unlocking shared lock: %w", err)
}
if !released {
return ErrLockNotReleased
}
return nil
}