]> Sergey Matveev's repositories - btrtrc.git/blob - storage/db.go
db95a11d29ae26fa642fd8f59cbd4512df4f7b8f
[btrtrc.git] / storage / db.go
1 package storage
2
3 import (
4         "database/sql"
5         "path/filepath"
6
7         "github.com/anacrolix/torrent/metainfo"
8 )
9
10 type dbPieceCompletion struct {
11         db *sql.DB
12 }
13
14 func newDBPieceCompletion(dir string) (ret *dbPieceCompletion, err error) {
15         p := filepath.Join(dir, ".torrent.db")
16         db, err := sql.Open("sqlite3", p)
17         if err != nil {
18                 return
19         }
20         _, err = db.Exec(`create table if not exists completed(infohash, "index", unique(infohash, "index") on conflict ignore)`)
21         if err != nil {
22                 db.Close()
23                 return
24         }
25         ret = &dbPieceCompletion{db}
26         return
27 }
28
29 func (me *dbPieceCompletion) Get(p metainfo.Piece) (ret bool, err error) {
30         row := me.db.QueryRow(`select exists(select * from completed where infohash=? and "index"=?)`, p.Info.Hash().HexString(), p.Index())
31         err = row.Scan(&ret)
32         return
33 }
34
35 func (me *dbPieceCompletion) Set(p metainfo.Piece, b bool) (err error) {
36         if b {
37                 _, err = me.db.Exec(`insert into completed (infohash, "index") values (?, ?)`, p.Info.Hash().HexString(), p.Index())
38         } else {
39                 _, err = me.db.Exec(`delete from completed where infohash=? and "index"=?`, p.Info.Hash().HexString(), p.Index())
40         }
41         return
42 }
43
44 func (me *dbPieceCompletion) Close() {
45         me.db.Close()
46 }