2016-10-25 16:54:09 +08:00
|
|
|
// +build cgo
|
|
|
|
|
2016-06-20 15:51:05 +08:00
|
|
|
package storage
|
|
|
|
|
|
|
|
import (
|
|
|
|
"database/sql"
|
|
|
|
"path/filepath"
|
|
|
|
|
2016-09-16 09:19:26 +08:00
|
|
|
_ "github.com/mattn/go-sqlite3"
|
|
|
|
|
2016-06-20 15:51:05 +08:00
|
|
|
"github.com/anacrolix/torrent/metainfo"
|
|
|
|
)
|
|
|
|
|
2016-10-25 16:07:26 +08:00
|
|
|
type sqlitePieceCompletion struct {
|
2016-06-20 15:51:05 +08:00
|
|
|
db *sql.DB
|
|
|
|
}
|
|
|
|
|
2018-01-11 19:10:00 +08:00
|
|
|
var _ PieceCompletion = (*sqlitePieceCompletion)(nil)
|
|
|
|
|
2018-01-12 08:09:33 +08:00
|
|
|
func NewSqlitePieceCompletion(dir string) (ret *sqlitePieceCompletion, err error) {
|
2016-06-20 15:51:05 +08:00
|
|
|
p := filepath.Join(dir, ".torrent.db")
|
|
|
|
db, err := sql.Open("sqlite3", p)
|
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
2018-01-11 19:10:00 +08:00
|
|
|
db.SetMaxOpenConns(1)
|
|
|
|
db.Exec(`PRAGMA journal_mode=WAL`)
|
|
|
|
db.Exec(`PRAGMA synchronous=1`)
|
|
|
|
_, err = db.Exec(`create table if not exists piece_completion(infohash, "index", complete, unique(infohash, "index"))`)
|
2016-06-20 15:51:05 +08:00
|
|
|
if err != nil {
|
|
|
|
db.Close()
|
|
|
|
return
|
|
|
|
}
|
2016-10-25 16:07:26 +08:00
|
|
|
ret = &sqlitePieceCompletion{db}
|
2016-06-20 15:51:05 +08:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2018-01-11 19:10:00 +08:00
|
|
|
func (me *sqlitePieceCompletion) Get(pk metainfo.PieceKey) (c Completion, err error) {
|
|
|
|
row := me.db.QueryRow(`select complete from piece_completion where infohash=? and "index"=?`, pk.InfoHash.HexString(), pk.Index)
|
|
|
|
err = row.Scan(&c.Complete)
|
|
|
|
if err == sql.ErrNoRows {
|
|
|
|
err = nil
|
|
|
|
} else if err == nil {
|
|
|
|
c.Ok = true
|
|
|
|
}
|
2016-06-20 15:51:05 +08:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2018-01-11 19:10:00 +08:00
|
|
|
func (me *sqlitePieceCompletion) Set(pk metainfo.PieceKey, b bool) error {
|
|
|
|
_, err := me.db.Exec(`insert or replace into piece_completion(infohash, "index", complete) values(?, ?, ?)`, pk.InfoHash.HexString(), pk.Index, b)
|
|
|
|
return err
|
2016-06-20 15:51:05 +08:00
|
|
|
}
|
|
|
|
|
2018-01-11 19:10:00 +08:00
|
|
|
func (me *sqlitePieceCompletion) Close() error {
|
|
|
|
return me.db.Close()
|
2016-06-20 15:51:05 +08:00
|
|
|
}
|