summaryrefslogtreecommitdiff
path: root/system/db/index.go
diff options
context:
space:
mode:
authorSteve <nilslice@gmail.com>2017-02-06 11:47:27 -0800
committerGitHub <noreply@github.com>2017-02-06 11:47:27 -0800
commit8da338b766f9a3035f89ca1f89367b0bc5a23f06 (patch)
tree7439cb9c4e0430bb51e5fe3217ca5630c8c5f4ad /system/db/index.go
parente9747661400953c20f0c9ee7fd3aa003ae8c44af (diff)
[core] add support for DB indexes (#62)
* fix typo in log message * update namespace to use prefix __index_ to avoid possible user conflicts
Diffstat (limited to 'system/db/index.go')
-rw-r--r--system/db/index.go85
1 files changed, 85 insertions, 0 deletions
diff --git a/system/db/index.go b/system/db/index.go
new file mode 100644
index 0000000..6a2727a
--- /dev/null
+++ b/system/db/index.go
@@ -0,0 +1,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
+}