-
Notifications
You must be signed in to change notification settings - Fork 1
/
pgstore.go
82 lines (67 loc) · 1.92 KB
/
pgstore.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
package claimsstore
import (
"github.com/iden3/go-iden3-core/db"
"github.com/jinzhu/gorm"
)
// PGStore is an implementation of the iden3 storage interface that uses postgres as its backend
type PGStore struct {
NodePersister *NodePGPersister
prefix []byte
}
// NewPGStore returns a new postgress store
func NewPGStore(nodePersister *NodePGPersister) *PGStore {
return &PGStore{
NodePersister: nodePersister,
}
}
// NewTx creates a new transaction
func (s *PGStore) NewTx() (db.Tx, error) {
kv := newKvMap()
return &PGTX{s, kv}, nil
}
// WithPrefix returns a new instance of the pgstore using the passed in prefix
func (s *PGStore) WithPrefix(prefix []byte) db.Storage {
return &PGStore{NodePersister: s.NodePersister, prefix: Concat(s.prefix, prefix)}
}
// Get gets the data from a node with the given key from the db
func (s *PGStore) Get(b []byte) ([]byte, error) {
key := Concat(s.prefix, b)
value, err := s.NodePersister.Get(key)
if gorm.IsRecordNotFoundError(err) {
return nil, db.ErrNotFound
}
bvalue, err := value.ToDataBytes()
return bvalue, err
}
// List lists all nodes for prefix/did
func (s *PGStore) List(limit int) ([]db.KV, error) {
return s.NodePersister.GetAllForPrefix(s.prefix, limit)
}
// Close closes the db
func (s PGStore) Close() {
err := s.NodePersister.DB.Close()
if err != nil {
panic(err)
}
}
// Info prints general information about all trees in the db
func (s *PGStore) Info() string {
return s.NodePersister.Info()
}
// Iterate performs a function on all nodes in all trees
func (s *PGStore) Iterate(f func([]byte, []byte) (bool, error)) error {
// WARNING iterate doesn't use the prefix
// in the future probably want to do this in a way that doesn't load them all into memory
kvs, err := s.NodePersister.GetAll()
if err != nil {
return err
}
for _, kv := range kvs {
if cont, err := f(kv.K, kv.V); err != nil {
return err
} else if !cont {
break
}
}
return nil
}