23 "crawshaw.io/sqlite/sqlitex"
24 "github.com/anacrolix/missinggo/iter"
25 "github.com/anacrolix/missinggo/v2/resource"
27 "github.com/anacrolix/torrent/storage"
30 type conn = *sqlite.Conn
32 type InitConnOpts struct {
35 MmapSizeOk bool // If false, a package-specific default will be used.
36 MmapSize int64 // If MmapSizeOk is set, use sqlite default if < 0, otherwise this value.
39 type UnexpectedJournalMode struct {
43 func (me UnexpectedJournalMode) Error() string {
44 return fmt.Sprintf("unexpected journal mode: %q", me.JournalMode)
47 func setSynchronous(conn conn, syncInt int) (err error) {
48 err = sqlitex.ExecTransient(conn, fmt.Sprintf(`pragma synchronous=%v`, syncInt), nil)
56 err = sqlitex.ExecTransient(conn, `pragma synchronous`, func(stmt *sqlite.Stmt) error {
57 actual = stmt.ColumnInt(0)
65 return errors.New("synchronous setting query didn't return anything")
67 if actual != syncInt {
68 return fmt.Errorf("set synchronous %q, got %q", syncInt, actual)
73 func initConn(conn conn, opts InitConnOpts) (err error) {
74 err = setSynchronous(conn, opts.SetSynchronous)
78 // Recursive triggers are required because we need to trim the blob_meta size after trimming to
79 // capacity. Hopefully we don't hit the recursion limit, and if we do, there's an error thrown.
80 err = sqlitex.ExecTransient(conn, "pragma recursive_triggers=on", nil)
84 if opts.SetJournalMode != "" {
85 err = sqlitex.ExecTransient(conn, fmt.Sprintf(`pragma journal_mode=%s`, opts.SetJournalMode), func(stmt *sqlite.Stmt) error {
86 ret := stmt.ColumnText(0)
87 if ret != opts.SetJournalMode {
88 return UnexpectedJournalMode{ret}
97 // Set the default. Currently it seems the library picks reasonable defaults, especially for
100 //opts.MmapSize = 1 << 24 // 8 MiB
102 if opts.MmapSize >= 0 {
103 err = sqlitex.ExecTransient(conn, fmt.Sprintf(`pragma mmap_size=%d`, opts.MmapSize), nil)
111 func setPageSize(conn conn, pageSize int) error {
116 err := sqlitex.ExecTransient(conn, fmt.Sprintf(`pragma page_size=%d`, pageSize), nil)
120 err = sqlitex.ExecTransient(conn, "pragma page_size", func(stmt *sqlite.Stmt) error {
121 retSize = stmt.ColumnInt64(0)
127 if retSize != int64(pageSize) {
128 return fmt.Errorf("requested page size %v but got %v", pageSize, retSize)
133 func InitSchema(conn conn, pageSize int, triggers bool) error {
134 err := setPageSize(conn, pageSize)
136 return fmt.Errorf("setting page size: %w", err)
138 err = sqlitex.ExecScript(conn, `
139 -- We have to opt into this before creating any tables, or before a vacuum to enable it. It means we
140 -- can trim the database file size with partial vacuums without having to do a full vacuum, which
142 pragma auto_vacuum=incremental;
144 create table if not exists blob (
146 last_used timestamp default (datetime('now')),
152 create table if not exists blob_meta (
153 key text primary key,
157 create index if not exists blob_last_used on blob(last_used);
159 -- While sqlite *seems* to be faster to get sum(length(data)) instead of
160 -- sum(length(data)), it may still require a large table scan at start-up or with a
161 -- cold-cache. With this we can be assured that it doesn't.
162 insert or ignore into blob_meta values ('size', 0);
164 create table if not exists setting (
165 name primary key on conflict replace,
169 create view if not exists deletable_blob as
170 with recursive excess (
179 (select value from blob_meta where key='size') as usage_with,
183 from blob order by last_used, rowid limit 1
185 where usage_with > (select value from setting where name='capacity')
188 usage_with-data_length as new_usage_with,
192 from excess join blob
193 on blob.rowid=(select rowid from blob where (last_used, rowid) > (excess.last_used, blob_rowid))
194 where new_usage_with > (select value from setting where name='capacity')
196 select * from excess;
202 err := sqlitex.ExecScript(conn, `
203 create trigger if not exists after_insert_blob
206 update blob_meta set value=value+length(cast(new.data as blob)) where key='size';
207 delete from blob where rowid in (select blob_rowid from deletable_blob);
210 create trigger if not exists after_update_blob
211 after update of data on blob
213 update blob_meta set value=value+length(cast(new.data as blob))-length(cast(old.data as blob)) where key='size';
214 delete from blob where rowid in (select blob_rowid from deletable_blob);
217 create trigger if not exists after_delete_blob
220 update blob_meta set value=value-length(cast(old.data as blob)) where key='size';
230 type NewPiecesStorageOpts struct {
233 ProvOpts func(*ProviderOpts)
234 StorageOpts func(*storage.ResourcePiecesOpts)
237 // A convenience function that creates a connection pool, resource provider, and a pieces storage
238 // ClientImpl and returns them all with a Close attached.
239 func NewPiecesStorage(opts NewPiecesStorageOpts) (_ storage.ClientImplCloser, err error) {
240 conns, err := NewPool(opts.NewPoolOpts)
244 if opts.PageSize == 0 {
245 opts.PageSize = 1 << 14
247 err = initPoolDatabase(conns, opts.InitDbOpts)
252 if opts.SetJournalMode == "" && !opts.Memory {
253 opts.SetJournalMode = "wal"
255 err = initPoolConns(nil, conns, opts.InitConnOpts)
260 provOpts := ProviderOpts{
261 BatchWrites: conns.NumConns() > 1,
263 if f := opts.ProvOpts; f != nil {
266 prov, err := NewProvider(conns, provOpts)
274 withPoolConn(conns, func(c conn) {
275 err = sqlitex.Exec(c, "pragma journal_mode", func(stmt *sqlite.Stmt) error {
276 journalMode = stmt.ColumnText(0)
281 err = fmt.Errorf("getting journal mode: %w", err)
285 if journalMode == "" {
286 err = errors.New("didn't get journal mode")
290 storageOpts := storage.ResourcePiecesOpts{
291 NoSizedPuts: journalMode != "wal" || conns.NumConns() == 1,
293 if f := opts.StorageOpts; f != nil {
296 store := storage.NewResourcePiecesOpts(prov, storageOpts)
306 type NewPoolOpts struct {
312 type InitDbOpts struct {
315 // If non-zero, overrides the existing setting.
320 // There's some overlap here with NewPoolOpts, and I haven't decided what needs to be done. For now,
321 // the fact that the pool opts are a superset, means our helper NewPiecesStorage can just take the
322 // top-level option type.
323 type PoolConf struct {
328 // Remove any capacity limits.
329 func UnlimitCapacity(conn conn) error {
330 return sqlitex.Exec(conn, "delete from setting where key='capacity'", nil)
333 // Set the capacity limit to exactly this value.
334 func SetCapacity(conn conn, cap int64) error {
335 return sqlitex.Exec(conn, "insert into setting values ('capacity', ?)", nil, cap)
338 type NewConnOpts struct {
339 // See https://www.sqlite.org/c3ref/open.html. NB: "If the filename is an empty string, then a
340 // private, temporary on-disk database will be created. This private database will be
341 // automatically deleted as soon as the database connection is closed."
344 // Whether multiple blobs will not be read simultaneously. Enables journal mode other than WAL,
346 NoConcurrentBlobReads bool
349 func newOpenUri(opts NewConnOpts) string {
350 path := url.PathEscape(opts.Path)
354 values := make(url.Values)
355 if opts.NoConcurrentBlobReads || opts.Memory {
356 values.Add("cache", "shared")
358 return fmt.Sprintf("file:%s?%s", path, values.Encode())
361 func initDatabase(conn conn, opts InitDbOpts) (err error) {
362 if !opts.DontInitSchema {
363 err = InitSchema(conn, opts.PageSize, !opts.NoTriggers)
368 if opts.Capacity != 0 {
369 err = SetCapacity(conn, opts.Capacity)
377 func initPoolDatabase(pool ConnPool, opts InitDbOpts) (err error) {
378 withPoolConn(pool, func(c conn) {
379 err = initDatabase(c, opts)
384 // Go fmt, why you so shit?
385 const openConnFlags = 0 |
386 sqlite.SQLITE_OPEN_READWRITE |
387 sqlite.SQLITE_OPEN_CREATE |
388 sqlite.SQLITE_OPEN_URI |
389 sqlite.SQLITE_OPEN_NOMUTEX
391 func newConn(opts NewConnOpts) (conn, error) {
392 return sqlite.OpenConn(newOpenUri(opts), openConnFlags)
395 type poolWithNumConns struct {
400 func (me poolWithNumConns) NumConns() int {
404 func NewPool(opts NewPoolOpts) (_ ConnPool, err error) {
405 if opts.NumConns == 0 {
406 opts.NumConns = runtime.NumCPU()
408 switch opts.NumConns {
410 conn, err := newConn(opts.NewConnOpts)
411 return &poolFromConn{conn: conn}, err
413 _pool, err := sqlitex.Open(newOpenUri(opts.NewConnOpts), openConnFlags, opts.NumConns)
414 return poolWithNumConns{_pool, opts.NumConns}, err
418 // Emulates a ConnPool from a single Conn. Might be faster than using a sqlitex.Pool.
419 type poolFromConn struct {
424 func (me *poolFromConn) Get(ctx context.Context) conn {
429 func (me *poolFromConn) Put(conn conn) {
431 panic("expected to same conn")
436 func (me *poolFromConn) Close() error {
437 return me.conn.Close()
440 func (poolFromConn) NumConns() int { return 1 }
442 type ProviderOpts struct {
446 // Needs the ConnPool size so it can initialize all the connections with pragmas. Takes ownership of
447 // the ConnPool (since it has to initialize all the connections anyway).
448 func NewProvider(pool ConnPool, opts ProviderOpts) (_ *provider, err error) {
449 prov := &provider{pool: pool, opts: opts}
450 if opts.BatchWrites {
451 writes := make(chan writeRequest)
453 // This is retained for backwards compatibility. It may not be necessary.
454 runtime.SetFinalizer(prov, func(p *provider) {
457 go providerWriter(writes, prov.pool)
462 type InitPoolOpts struct {
467 func initPoolConns(ctx context.Context, pool ConnPool, opts InitConnOpts) (err error) {
470 for _, c := range conns {
474 for range iter.N(pool.NumConns()) {
475 conn := pool.Get(ctx)
479 conns = append(conns, conn)
480 err = initConn(conn, opts)
482 err = fmt.Errorf("initing conn %v: %w", len(conns), err)
489 type ConnPool interface {
490 Get(context.Context) conn
496 func withPoolConn(pool ConnPool, with func(conn)) {
502 type provider struct {
504 writes chan<- writeRequest
511 var _ storage.ConsecutiveChunkReader = (*provider)(nil)
513 func (p *provider) ReadConsecutiveChunks(prefix string) (io.ReadCloser, error) {
515 runner, err := p.getReadWithConnRunner()
522 defer p.closeMu.RUnlock()
523 err = runner(func(_ context.Context, conn conn) error {
525 err = sqlitex.Exec(conn, `
528 cast(substr(name, ?+1) as integer) as offset
530 where name like ?||'%'
532 func(stmt *sqlite.Stmt) error {
533 offset := stmt.ColumnInt64(1)
534 if offset != written {
535 return fmt.Errorf("got chunk at offset %v, expected offset %v", offset, written)
537 // TODO: Avoid intermediate buffers here
538 r := stmt.ColumnReader(0)
539 w1, err := io.Copy(w, r)
548 w.CloseWithError(err)
553 func (me *provider) Close() error {
555 defer me.closeMu.Unlock()
559 if me.writes != nil {
562 me.closeErr = me.pool.Close()
567 type writeRequest struct {
570 labels pprof.LabelSet
573 var expvars = expvar.NewMap("sqliteStorage")
575 func runQueryWithLabels(query withConn, labels pprof.LabelSet, conn conn) (err error) {
576 pprof.Do(context.Background(), labels, func(ctx context.Context) {
577 // We pass in the context in the hope that the CPU profiler might incorporate sqlite
578 // activity the action that triggered it. It doesn't seem that way, since those calls don't
579 // take a context.Context themselves. It may come in useful in the goroutine profiles
580 // though, and doesn't hurt to expose it here for other purposes should things change.
581 err = query(ctx, conn)
586 // Intentionally avoids holding a reference to *provider to allow it to use a finalizer, and to have
587 // stronger typing on the writes channel.
588 func providerWriter(writes <-chan writeRequest, pool ConnPool) {
589 conn := pool.Get(context.TODO())
595 first, ok := <-writes
602 defer sqlitex.Save(conn)(&cantFail)
603 firstErr := runQueryWithLabels(first.query, first.labels, conn)
604 buf = append(buf, func() { first.done <- firstErr })
607 case wr, ok := <-writes:
609 err := runQueryWithLabels(wr.query, wr.labels, conn)
610 buf = append(buf, func() { wr.done <- err })
618 // Not sure what to do if this failed.
620 expvars.Add("batchTransactionErrors", 1)
622 // Signal done after we know the transaction succeeded.
623 for _, done := range buf {
626 expvars.Add("batchTransactions", 1)
627 expvars.Add("batchedQueries", int64(len(buf)))
628 //log.Printf("batched %v write queries", len(buf))
632 func (p *provider) NewInstance(s string) (resource.Instance, error) {
633 return instance{s, p}, nil
636 type instance struct {
641 func getLabels(skip int) pprof.LabelSet {
642 return pprof.Labels("sqlite-storage-action", func() string {
644 runtime.Callers(skip+3, pcs[:])
645 fs := runtime.CallersFrames(pcs[:])
647 funcName := f.Func.Name()
648 funcName = funcName[strings.LastIndexByte(funcName, '.')+1:]
649 //log.Printf("func name: %q", funcName)
654 func (p *provider) withConn(with withConn, write bool, skip int) error {
656 // I think we need to check this here because it may not be valid to send to the writes channel
657 // if we're already closed. So don't try to move this check into getReadWithConnRunner.
660 return errors.New("closed")
662 if write && p.opts.BatchWrites {
663 done := make(chan error)
664 p.writes <- writeRequest{
667 labels: getLabels(skip + 1),
672 defer p.closeMu.RUnlock()
673 runner, err := p.getReadWithConnRunner()
681 // Obtains a DB conn and returns a withConn for executing with it. If no error is returned from this
682 // function, the runner *must* be used or the conn is leaked. You should check the provider isn't
683 // closed before using this.
684 func (p *provider) getReadWithConnRunner() (with func(withConn) error, err error) {
685 conn := p.pool.Get(context.TODO())
687 err = errors.New("couldn't get pool conn")
690 with = func(with withConn) error {
691 defer p.pool.Put(conn)
692 return runQueryWithLabels(with, getLabels(1), conn)
697 type withConn func(context.Context, conn) error
699 func (i instance) withConn(with withConn, write bool) error {
700 return i.p.withConn(with, write, 1)
703 func (i instance) getConn() *sqlite.Conn {
704 return i.p.pool.Get(context.TODO())
707 func (i instance) putConn(conn *sqlite.Conn) {
711 func (i instance) Readdirnames() (names []string, err error) {
712 prefix := i.location + "/"
713 err = i.withConn(func(_ context.Context, conn conn) error {
714 return sqlitex.Exec(conn, "select name from blob where name like ?", func(stmt *sqlite.Stmt) error {
715 names = append(names, stmt.ColumnText(0)[len(prefix):])
719 //log.Printf("readdir %q gave %q", i.location, names)
723 func (i instance) getBlobRowid(conn conn) (rowid int64, err error) {
725 err = sqlitex.Exec(conn, "select rowid from blob where name=?", func(stmt *sqlite.Stmt) error {
726 rowid = stmt.ColumnInt64(0)
737 err = errors.New("blob not found")
743 type connBlob struct {
748 func (me connBlob) Close() error {
749 err := me.Blob.Close()
754 func (i instance) Get() (ret io.ReadCloser, err error) {
757 panic("nil sqlite conn")
759 blob, err := i.openBlob(conn, false, true)
765 return connBlob{blob, func() {
766 once.Do(func() { i.putConn(conn) })
770 func (i instance) openBlob(conn conn, write, updateAccess bool) (*sqlite.Blob, error) {
771 rowid, err := i.getBlobRowid(conn)
775 // This seems to cause locking issues with in-memory databases. Is it something to do with not
778 err = sqlitex.Exec(conn, "update blob set last_used=datetime('now') where rowid=?", nil, rowid)
780 err = fmt.Errorf("updating last_used: %w", err)
783 if conn.Changes() != 1 {
784 panic(conn.Changes())
787 return conn.OpenBlob("main", "blob", "data", rowid, write)
790 func (i instance) PutSized(reader io.Reader, size int64) (err error) {
791 err = i.withConn(func(_ context.Context, conn conn) error {
792 err := sqlitex.Exec(conn, "insert or replace into blob(name, data) values(?, zeroblob(?))",
798 blob, err := i.openBlob(conn, true, false)
803 _, err = io.Copy(blob, reader)
809 func (i instance) Put(reader io.Reader) (err error) {
811 _, err = io.Copy(&buf, reader)
816 return i.PutSized(&buf, int64(buf.Len()))
818 return i.withConn(func(_ context.Context, conn conn) error {
819 for range iter.N(10) {
820 err = sqlitex.Exec(conn,
821 "insert or replace into blob(name, data) values(?, cast(? as blob))",
823 i.location, buf.Bytes())
824 if err, ok := err.(sqlite.Error); ok && err.Code == sqlite.SQLITE_BUSY {
825 log.Print("sqlite busy")
826 time.Sleep(time.Second)
836 type fileInfo struct {
840 func (f fileInfo) Name() string {
841 panic("implement me")
844 func (f fileInfo) Size() int64 {
848 func (f fileInfo) Mode() os.FileMode {
849 panic("implement me")
852 func (f fileInfo) ModTime() time.Time {
853 panic("implement me")
856 func (f fileInfo) IsDir() bool {
857 panic("implement me")
860 func (f fileInfo) Sys() interface{} {
861 panic("implement me")
864 func (i instance) Stat() (ret os.FileInfo, err error) {
865 err = i.withConn(func(_ context.Context, conn conn) error {
866 var blob *sqlite.Blob
867 blob, err = i.openBlob(conn, false, false)
872 ret = fileInfo{blob.Size()}
878 func (i instance) ReadAt(p []byte, off int64) (n int, err error) {
879 err = i.withConn(func(_ context.Context, conn conn) error {
881 var blob *sqlite.Blob
882 blob, err = i.openBlob(conn, false, true)
887 if off >= blob.Size() {
891 if off+int64(len(p)) > blob.Size() {
892 p = p[:blob.Size()-off]
894 n, err = blob.ReadAt(p, off)
899 "select substr(data, ?, ?) from blob where name=?",
900 func(stmt *sqlite.Stmt) error {
902 panic("found multiple matching blobs")
906 n = stmt.ColumnBytes(0, p)
909 off+1, len(p), i.location,
915 err = errors.New("blob not found")
927 func (i instance) WriteAt(bytes []byte, i2 int64) (int, error) {
928 panic("implement me")
931 func (i instance) Delete() error {
932 return i.withConn(func(_ context.Context, conn conn) error {
933 return sqlitex.Exec(conn, "delete from blob where name=?", nil, i.location)