mark/model.go

87 lines
2.0 KiB
Go
Raw Normal View History

2017-09-20 22:12:17 +00:00
package main
import (
"errors"
"github.com/br0xen/boltease"
)
// model.go contains some basic database stuff
// MarkDB is an abstraction of a boltease.DB (which is an abstraction of
// a bolt.DB)
type MarkDB struct {
db *boltease.DB
dbOpened int // Track how many 'open' requests are outstanding
path, filename string
}
func NewDatabase(path, name string) (*MarkDB, error) {
if path[len(path)-1] != '/' {
path = path + "/"
}
mdb := MarkDB{
path: path,
filename: name,
}
return &mdb, nil
}
func (mdb *MarkDB) openDatabase() error {
mdb.dbOpened += 1
if mdb.dbOpened == 1 {
// We actually need to open the DB
var err error
mdb.db, err = boltease.Create(mdb.path+mdb.filename, 0600, nil)
if err != nil {
return err
}
}
return nil
}
func (mdb *MarkDB) closeDatabase() error {
mdb.dbOpened -= 1
if mdb.dbOpened == 0 {
// Actually close the database
return mdb.db.CloseDB()
}
return nil
}
func (mdb *MarkDB) initDatabase() error {
var err error
if err = mdb.openDatabase(); err != nil {
return err
}
defer mdb.closeDatabase()
// Create the path to the bucket to store bookmarks
if err = mdb.db.MkBucketPath([]string{"bookmarks"}); err != nil {
return errors.New("Error creating 'bookmarks' bucket: " + err.Error())
}
// Create the path to the bucket to store additional config
if err = mdb.db.MkBucketPath([]string{"config"}); err != nil {
return errors.New("Error creating 'config' bucket: " + err.Error())
}
if err = mdb.db.SetInt([]string{"config"}, "lastIdx", 0); err != nil {
return errors.New("Error setting 'lastIdx' to 0: " + err.Error())
}
return nil
}
2017-09-21 14:46:59 +00:00
// GetLastIndex returns the last used index for a bookmark
// If we had a problem getting it, we return the error
func (mdb *MarkDB) GetLastIndex() (int, error) {
return mdb.db.GetInt([]string{"config"}, "lastIdx")
}
// GetNextIndex returns the next available index for a bookmark
func (mdb *MarkDB) GetNextIndex() int {
idx, err := mdb.GetLastIndex()
if err != nil {
return -1
}
return idx + 1
2017-09-20 22:12:17 +00:00
}