/
psqllockstatedb.go
46 lines (37 loc) 路 1.06 KB
/
psqllockstatedb.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
package db
import (
"context"
"github.com/anacrolix/torrent/metainfo"
"github.com/jackc/pgx/v4/pgxpool"
)
type PsqlLsDb struct {
Db *pgxpool.Pool
}
func (db *PsqlLsDb) Open(dburl string) {
var err error
db.Db, err = pgxpool.Connect(context.Background(), dburl)
if err != nil {
DbL.Fatalln(err)
}
_, err = db.Db.Exec(context.Background(), `create table if not exists lockstatedb (infohash text primary key);`)
if err != nil {
DbL.Fatalln(err)
}
}
func (db *PsqlLsDb) Close() {
db.Db.Close()
}
func (db *PsqlLsDb) Lock(m metainfo.Hash) (err error) {
_, err = db.Db.Exec(context.Background(), `insert into lockstatedb (infohash) values ($1) on conflict (infohash) do nothing;`, m.HexString())
return
}
func (db *PsqlLsDb) Unlock(m metainfo.Hash) (err error) {
_, err = db.Db.Exec(context.Background(), `delete from lockstatedb where infohash=$1;`, m.HexString())
return
}
func (db *PsqlLsDb) IsLocked(m string) (b bool) {
if db.Db.QueryRow(context.Background(), `select true from lockstatedb where infohash=$1;`, m).Scan(&b) != nil {
return false
}
return
}