summaryrefslogtreecommitdiff
path: root/system/db/index.go
blob: 6a2727a0d27ece495577edf01c3849e56f232bd2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package db

import (
	"bytes"
	"encoding/json"

	"github.com/boltdb/bolt"
)

// Index gets the value from the namespace at the key provided
func Index(namespace, key string) ([]byte, error) {
	val := &bytes.Buffer{}
	err := store.View(func(tx *bolt.Tx) error {
		b := tx.Bucket([]byte(index(namespace)))
		if b == nil {
			return nil
		}

		v := b.Get([]byte(key))

		_, err := val.Write(v)
		if err != nil {
			return err
		}

		return nil
	})
	if err != nil {
		return nil, err
	}

	return val.Bytes(), nil
}

// SetIndex sets a key/value pair within the namespace provided and will return
// an error if it fails
func SetIndex(namespace, key string, value interface{}) error {
	return store.Update(func(tx *bolt.Tx) error {
		b, err := tx.CreateBucketIfNotExists([]byte(index(namespace)))
		if err != nil {
			return err
		}

		val, err := json.Marshal(value)
		if err != nil {
			return err
		}

		return b.Put([]byte(key), val)
	})
}

// DeleteIndex removes the key and value from the namespace provided and will
// return an error if it fails. It will return nil if there was no key/value in
// the index to delete.
func DeleteIndex(namespace, key string) error {
	return store.Update(func(tx *bolt.Tx) error {
		b := tx.Bucket([]byte(index(namespace)))
		if b == nil {
			return nil
		}

		return b.Delete([]byte(key))
	})
}

// DropIndex removes the index and all key/value pairs in the namespace index
func DropIndex(namespace string) error {
	return store.Update(func(tx *bolt.Tx) error {
		err := tx.DeleteBucket([]byte(index(namespace)))
		if err == bolt.ErrBucketNotFound {
			return nil
		}

		if err != nil {
			return err
		}

		return nil
	})
}

func index(namespace string) string {
	return "__index_" + namespace
}