This repository has been archived by the owner on Apr 21, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
badger.go
82 lines (67 loc) · 1.55 KB
/
badger.go
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
// Low-level operations on the database.
package main
import (
"fmt"
badger "github.com/dgraph-io/badger"
)
func badgerSet(db *badger.DB, repo Repo) error {
return db.Update(func(txn *badger.Txn) error {
// Encode
bytes, err := repo.encode()
if err != nil {
return err
}
// Save
err = txn.Set([]byte(repo.URL), bytes)
return err
})
}
// badgerList populates a channel with every single keys inside the Badger database.
func badgerList(db *badger.DB, ch chan repoerr) error {
err := db.View(func(txn *badger.Txn) error {
it := txn.NewIterator(badger.DefaultIteratorOptions)
defer it.Close()
for it.Rewind(); it.Valid(); it.Next() {
item := it.Item()
err := item.Value(func(v []byte) error {
repo, err := decodeRepo(v)
ch <- repoerr{
repo: repo,
err: err,
}
return err
})
// Continue even if there's an error
if err != nil {
fmt.Println("Couldn't get the value of an item.")
fmt.Println(err.Error())
}
}
return nil
})
close(ch)
return err
}
// Get a repository from its URL.
//
// Can return `badger.ErrKeyNotFound`.
func badgerGet(db *badger.DB, link string, ch chan Repo) error {
err := db.View(func(txn *badger.Txn) error {
item, err := txn.Get([]byte(link))
if err != nil {
return err
}
return item.Value(func(bytes []byte) error {
repo, err := decodeRepo(bytes)
ch <- repo
return err
})
})
close(ch)
return err
}
func badgerDelete(db *badger.DB, link string) error {
return db.Update(func(txn *badger.Txn) error {
return txn.Delete([]byte(link))
})
}