feta/database/manager.go

60 lines
1.2 KiB
Go
Raw Normal View History

2020-03-27 23:02:36 +00:00
package database
import (
"path/filepath"
"sync"
2020-03-27 23:02:36 +00:00
"github.com/jinzhu/gorm"
u "git.eeqj.de/sneak/goutil"
2020-03-27 23:02:36 +00:00
_ "github.com/jinzhu/gorm/dialects/sqlite"
"github.com/rs/zerolog/log"
"github.com/spf13/viper"
2020-04-05 01:17:35 +00:00
"github.com/golang/groupcache/lru"
2020-03-27 23:02:36 +00:00
)
2020-04-05 01:17:35 +00:00
const cacheEntries = 1000000
// Manager coordinates database and cache reads and writes
2020-03-27 23:02:36 +00:00
type Manager struct {
db *gorm.DB
cachelock sync.Mutex
2020-04-05 01:17:35 +00:00
recentlyInsertedTootHashCache *lru.Cache
2020-03-27 23:02:36 +00:00
}
2020-04-05 01:17:35 +00:00
// New creates new Manager
2020-03-27 23:02:36 +00:00
func New() *Manager {
m := new(Manager)
m.init()
return m
}
func (m *Manager) init() {
2020-03-28 01:17:52 +00:00
m.open()
// breaks stuff, do not use:
//m.db.SingularTable(true)
2020-03-27 23:46:47 +00:00
m.db.LogMode(false)
if viper.GetBool("Debug") {
m.db.LogMode(true)
}
2020-04-05 01:17:35 +00:00
m.recentlyInsertedTootHashCache = lru.New(cacheEntries)
2020-03-27 23:02:36 +00:00
}
func (m *Manager) open() {
log.Info().Msg("opening database")
dirname := filepath.Dir(viper.GetString("DbStorageLocation"))
err := u.Mkdirp(dirname)
2020-03-27 23:02:36 +00:00
if err != nil {
log.Panic().
Err(err).
Msg("db path erro")
}
db, err := gorm.Open("sqlite3", viper.GetString("DbStorageLocation"))
if err != nil {
log.Panic().
Err(err).
Msg("failed to open database")
}
m.db = db
m.doMigrations()
}