rpi-vsts-ci-led/pkg/database/database.go
2020-04-20 10:24:33 +08:00

56 lines
738 B
Go

package database
import (
"errors"
"os"
"path"
"git.trj.tw/golang/utils"
"go.etcd.io/bbolt"
)
var db *bbolt.DB
func New(dbPath ...string) error {
var err error
var fp string
if len(dbPath) > 0 && dbPath[0] != "" {
fp = dbPath[0]
} else {
wd, err := os.Getwd()
if err != nil {
return err
}
fp = path.Join(wd, "store.db")
}
fp = utils.ParsePath(fp)
db, err = bbolt.Open(fp, 0664, nil)
if err != nil {
return err
}
tx, err := db.Begin(true)
if err != nil {
return err
}
if _, err := tx.CreateBucketIfNotExists([]byte("led")); err != nil {
tx.Rollback()
return err
}
tx.Commit()
return nil
}
func Get() *bbolt.DB {
if db == nil {
panic(errors.New("database not init"))
}
return db
}