sqlite.go

 1package filesqlite
 2
 3import (
 4	"context"
 5	"errors"
 6	"fmt"
 7
 8	"github.com/charmbracelet/log"
 9	"github.com/charmbracelet/soft-serve/server/cache"
10	"github.com/charmbracelet/soft-serve/server/config"
11	"github.com/charmbracelet/soft-serve/server/db"
12	"github.com/charmbracelet/soft-serve/server/db/sqlite"
13	"github.com/charmbracelet/soft-serve/server/store"
14	"github.com/go-git/go-billy/v5"
15)
16
17var (
18	// ErrDbNotSqlite is returned when the database is not a SQLite database.
19	ErrDbNotSqlite = errors.New("database is not a SQLite database")
20
21	// ErrRepoNotExist is returned when a repository does not exist.
22	ErrRepoNotExist = fmt.Errorf("repository does not exist")
23
24	// ErrRepoExist is returned when a repository already exists.
25	ErrRepoExist = fmt.Errorf("repository already exists")
26)
27
28// SqliteStore is a file-based SQLite store.
29type SqliteStore struct {
30	fs     billy.Filesystem
31	ctx    context.Context
32	cfg    *config.Config
33	db     db.Database
34	cache  cache.Cache
35	logger *log.Logger
36}
37
38var _ store.Store = (*SqliteStore)(nil)
39
40func init() {
41	store.Register("sqlite", newFileSqliteStore)
42}
43
44func newFileSqliteStore(ctx context.Context, fs billy.Filesystem) (store.Store, error) {
45	sdb := db.FromContext(ctx)
46	if sdb == nil {
47		return nil, db.ErrNoDatabase
48	}
49
50	if _, ok := sdb.(*sqlite.Sqlite); !ok {
51		return nil, ErrDbNotSqlite
52	}
53
54	ss := &SqliteStore{
55		fs:     fs,
56		ctx:    ctx,
57		db:     sdb,
58		logger: log.FromContext(ctx).WithPrefix("filesqlite"),
59		cfg:    config.FromContext(ctx),
60		cache:  cache.FromContext(ctx),
61	}
62
63	c := cache.FromContext(ctx)
64	if c == nil {
65		return nil, cache.ErrNotFound
66	}
67
68	return ss, nil
69}
70
71func (ss *SqliteStore) Filesystem() billy.Filesystem {
72	return ss.fs
73}
74
75func (ss *SqliteStore) reposPath() string {
76	return ss.fs.Root()
77}
78
79// cacheKey returns the cache key for a repository.
80func cacheKey(name string) string {
81	return fmt.Sprintf("repo:%s", name)
82}