all repos — paprika @ location

go rewrite of taigabot

database/db.go (view raw)

 1package database
 2
 3import (
 4	"github.com/dgraph-io/badger/v3"
 5)
 6
 7// Use this as a global DB handle.
 8var DB database
 9
10type database struct {
11	*badger.DB
12}
13
14func Open() (*badger.DB, error) {
15	db, err := badger.Open(badger.DefaultOptions("./badger"))
16	if err != nil {
17		return nil, err
18	}
19	return db, nil
20}
21
22// Wrapper function to simplify setting a key/val
23// in badger.
24func (d *database) Set(key, val []byte) error {
25	err := d.Update(func(txn *badger.Txn) error {
26		err := txn.Set(key, val)
27		return err
28	})
29
30	return err
31}
32
33// Wrapper function to simplify getting a key from badger.
34func (d *database) Get(key []byte) ([]byte, error) {
35	var val []byte
36	err := d.View(func(txn *badger.Txn) error {
37		item, err := txn.Get(key)
38		if err != nil {
39			return err
40		}
41
42		err = item.Value(func(v []byte) error {
43			val, err = item.ValueCopy(nil)
44			return err
45		})
46		return err
47	})
48	if err != nil {
49		return nil, err
50	}
51	return val, nil
52}