-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadvisory.go
More file actions
49 lines (39 loc) · 1.28 KB
/
Copy pathadvisory.go
File metadata and controls
49 lines (39 loc) · 1.28 KB
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
package xpg
import (
"context"
"errors"
"fmt"
"github.com/jackc/pgx/v5"
)
const (
advisoryXactLockSQL = "SELECT pg_advisory_xact_lock($1)"
tryAdvisoryXactLockSQL = "SELECT pg_try_advisory_xact_lock($1)"
)
// AdvisoryXactLock acquires an exclusive transaction-level advisory lock.
//
// The call blocks until the lock is acquired or ctx is canceled. PostgreSQL
// releases the lock automatically when tx is committed or rolled back.
func AdvisoryXactLock(ctx context.Context, tx pgx.Tx, key int64) error {
if tx == nil {
return errors.New("xpg: transaction is nil")
}
if _, err := tx.Exec(ctx, advisoryXactLockSQL, key); err != nil {
return fmt.Errorf("xpg: acquire transaction advisory lock: %w", err)
}
return nil
}
// TryAdvisoryXactLock attempts to acquire an exclusive transaction-level
// advisory lock without waiting.
//
// PostgreSQL releases an acquired lock automatically when tx is committed or
// rolled back.
func TryAdvisoryXactLock(ctx context.Context, tx pgx.Tx, key int64) (bool, error) {
if tx == nil {
return false, errors.New("xpg: transaction is nil")
}
var acquired bool
if err := tx.QueryRow(ctx, tryAdvisoryXactLockSQL, key).Scan(&acquired); err != nil {
return false, fmt.Errorf("xpg: try transaction advisory lock: %w", err)
}
return acquired, nil
}