forked from anacrolix/torrent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sqlitePieceCompletion.go
50 lines (41 loc) · 1.22 KB
/
sqlitePieceCompletion.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
// +build cgo
package storage
import (
"database/sql"
"path/filepath"
_ "github.com/mattn/go-sqlite3"
"github.com/anacrolix/torrent/metainfo"
)
type sqlitePieceCompletion struct {
db *sql.DB
}
func newSqlitePieceCompletion(dir string) (ret *sqlitePieceCompletion, err error) {
p := filepath.Join(dir, ".torrent.db")
db, err := sql.Open("sqlite3", p)
if err != nil {
return
}
_, err = db.Exec(`create table if not exists completed(infohash, "index", unique(infohash, "index") on conflict ignore)`)
if err != nil {
db.Close()
return
}
ret = &sqlitePieceCompletion{db}
return
}
func (me *sqlitePieceCompletion) Get(pk metainfo.PieceKey) (ret bool, err error) {
row := me.db.QueryRow(`select exists(select * from completed where infohash=? and "index"=?)`, pk.InfoHash.HexString(), pk.Index)
err = row.Scan(&ret)
return
}
func (me *sqlitePieceCompletion) Set(pk metainfo.PieceKey, b bool) (err error) {
if b {
_, err = me.db.Exec(`insert into completed (infohash, "index") values (?, ?)`, pk.InfoHash.HexString(), pk.Index)
} else {
_, err = me.db.Exec(`delete from completed where infohash=? and "index"=?`, pk.InfoHash.HexString(), pk.Index)
}
return
}
func (me *sqlitePieceCompletion) Close() {
me.db.Close()
}