60 lines
1.2 KiB
Go
60 lines
1.2 KiB
Go
package database
|
|
|
|
import (
|
|
"path/filepath"
|
|
"sync"
|
|
"github.com/jinzhu/gorm"
|
|
u "git.eeqj.de/sneak/goutil"
|
|
_ "github.com/jinzhu/gorm/dialects/sqlite"
|
|
"github.com/rs/zerolog/log"
|
|
"github.com/spf13/viper"
|
|
"github.com/golang/groupcache/lru"
|
|
)
|
|
|
|
const cacheEntries = 1000000
|
|
|
|
// Manager coordinates database and cache reads and writes
|
|
type Manager struct {
|
|
db *gorm.DB
|
|
cachelock sync.Mutex
|
|
recentlyInsertedTootHashCache *lru.Cache
|
|
}
|
|
|
|
// New creates new Manager
|
|
func New() *Manager {
|
|
m := new(Manager)
|
|
m.init()
|
|
return m
|
|
}
|
|
|
|
func (m *Manager) init() {
|
|
m.open()
|
|
// breaks stuff, do not use:
|
|
//m.db.SingularTable(true)
|
|
m.db.LogMode(false)
|
|
if viper.GetBool("Debug") {
|
|
m.db.LogMode(true)
|
|
}
|
|
m.recentlyInsertedTootHashCache = lru.New(cacheEntries)
|
|
}
|
|
|
|
func (m *Manager) open() {
|
|
log.Info().Msg("opening database")
|
|
dirname := filepath.Dir(viper.GetString("DbStorageLocation"))
|
|
err := u.Mkdirp(dirname)
|
|
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()
|
|
}
|