7 "crawshaw.io/sqlite/sqlitex"
8 "github.com/anacrolix/torrent/metainfo"
9 "github.com/anacrolix/torrent/storage"
12 type NewDirectStorageOpts struct {
14 ProvOpts func(*ProviderOpts)
17 // A convenience function that creates a connection pool, resource provider, and a pieces storage
18 // ClientImpl and returns them all with a Close attached.
19 func NewDirectStorage(opts NewDirectStorageOpts) (_ storage.ClientImplCloser, err error) {
20 conns, provOpts, err := NewPool(opts.NewPoolOpts)
24 if f := opts.ProvOpts; f != nil {
27 provOpts.BatchWrites = false
28 prov, err := NewProvider(conns, provOpts)
35 conn: prov.pool.Get(nil),
36 blobs: make(map[string]*sqlite.Blob),
44 blobs map[string]*sqlite.Blob
47 func (c *client) OpenTorrent(info *metainfo.Info, infoHash metainfo.Hash) (storage.TorrentImpl, error) {
48 return torrent{c}, nil
51 func (c *client) Close() error {
52 for _, b := range c.blobs {
55 c.prov.pool.Put(c.conn)
63 func rowidForBlob(c conn, name string, length int64) (rowid int64, err error) {
64 err = sqlitex.Exec(c, "select rowid from blob where name=?", func(stmt *sqlite.Stmt) error {
65 rowid = stmt.ColumnInt64(0)
74 err = sqlitex.Exec(c, "insert into blob(name, data) values(?, zeroblob(?))", nil, name, length)
78 rowid = c.LastInsertRowID()
82 func (t torrent) Piece(p metainfo.Piece) storage.PieceImpl {
85 name := p.Hash().HexString()
86 return piece{t.c.conn, &t.c.l, name, t.c.blobs, p.Length()}
89 func (t torrent) Close() error {
97 blobs map[string]*sqlite.Blob
101 func (p2 piece) ReadAt(p []byte, off int64) (n int, err error) {
105 return blob.ReadAt(p, off)
108 func (p2 piece) WriteAt(p []byte, off int64) (n int, err error) {
111 return p2.getBlob().WriteAt(p, off)
114 func (p2 piece) MarkComplete() error {
117 err := sqlitex.Exec(p2.conn, "update blob set verified=true where name=?", nil, p2.name)
121 changes := p2.conn.Changes()
129 func (p2 piece) blobWouldExpire() {
130 blob, ok := p2.blobs[p2.name]
135 delete(p2.blobs, p2.name)
138 func (p2 piece) MarkNotComplete() error {
140 return sqlitex.Exec(p2.conn, "update blob set verified=false where name=?", nil, p2.name)
143 func (p2 piece) Completion() (ret storage.Completion) {
146 err := sqlitex.Exec(p2.conn, "select verified from blob where name=?", func(stmt *sqlite.Stmt) error {
147 ret.Complete = stmt.ColumnInt(0) != 0
157 func (p2 piece) closeBlobIfExists() {
158 if b, ok := p2.blobs[p2.name]; ok {
160 delete(p2.blobs, p2.name)
164 func (p2 piece) getBlob() *sqlite.Blob {
165 blob, ok := p2.blobs[p2.name]
167 rowid, err := rowidForBlob(p2.conn, p2.name, p2.length)
171 blob, err = p2.conn.OpenBlob("main", "blob", "data", rowid, true)
175 p2.blobs[p2.name] = blob