-
Notifications
You must be signed in to change notification settings - Fork 0
/
locker.go
58 lines (45 loc) · 1.07 KB
/
locker.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
package glloq
import (
"context"
"database/sql"
"github.com/xo/dburl"
)
type Locker interface {
// SupportsDSN returns true if the DSN is supported by the Locker.
SupportsDSN(dsn string) bool
// Open allows the locker to open a connection to the backend.
Open(ctx context.Context, dsn string) error
// Close allows the locker to close the connection to the backend
Close() error
// Holds the lock. Returns ErrTimeout if context is done.
WithLock(ctx context.Context, opts *Options, fn func() error) error
}
// SQLLocker implements some base locker methods for SQL-based backends.
type SQLLocker struct {
DB *sql.DB
}
func (l *SQLLocker) DBUrlDriver(dsn string) string {
u, err := dburl.Parse(dsn)
if err != nil {
return ""
}
return u.Driver
}
func (l *SQLLocker) Open(ctx context.Context, dsn string) error {
db, err := dburl.Open(dsn)
if err != nil {
return err
}
if err := db.PingContext(ctx); err != nil {
defer db.Close()
return err
}
l.DB = db
return nil
}
func (l *SQLLocker) Close() error {
if l.DB != nil {
return l.DB.Close()
}
return nil
}