GoBroke/cachedb/funcs.go

74 lines
1.4 KiB
Go
Raw Normal View History

2024-12-17 17:39:10 -05:00
package cachedb
import (
`os`
`path/filepath`
`github.com/jmoiron/sqlx`
_ `github.com/mattn/go-sqlite3`
`r00t2.io/gobroke/conf`
2024-12-17 17:39:10 -05:00
`r00t2.io/sysutils/paths`
)
/*
NewCache returns a Cache from path to SQLite file `db` (or ":memory:" for an in-memory one).
It will be created if it doesn't exist for persistent caches.
*/
func NewCache(db string, perms *conf.Perms) (c *Cache, err error) {
2024-12-17 17:39:10 -05:00
var cache Cache
2024-12-17 17:39:10 -05:00
var exists bool
switch db {
case ":memory:":
// NO-OP for now; exists should be false, but it is since it's zero-val.
2024-12-17 17:39:10 -05:00
default:
if perms == nil {
perms = new(conf.Perms)
if err = perms.SetMissing(); err != nil {
return
}
}
2024-12-17 17:39:10 -05:00
if exists, err = paths.RealPathExists(&db); err != nil {
return
}
if !exists {
if err = os.MkdirAll(filepath.Dir(db), *perms.ParentDir.Mode); err != nil {
2024-12-17 17:39:10 -05:00
return
}
if err = os.WriteFile(db, nil, *perms.File.Mode); err != nil {
return
}
}
if err = perms.Chown(filepath.Dir(db)); err != nil {
return
}
if err = perms.Chmod(filepath.Dir(db), !exists); err != nil {
return
}
if err = perms.Chown(db); err != nil {
return
2024-12-17 17:39:10 -05:00
}
if err = perms.Chmod(db, !exists); err != nil {
return
}
}
if cache.db, err = sqlx.Connect("sqlite3", db); err != nil {
return
}
if !exists {
// New DB, so write the schema.
if _, err = cache.db.Exec(string(schemaBytes)); err != nil {
return
}
2024-12-17 17:39:10 -05:00
}
c = &cache
2024-12-17 17:39:10 -05:00
return
}