-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathstore.go
95 lines (78 loc) · 2.44 KB
/
store.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
83
84
85
86
87
88
89
90
91
92
93
94
95
package postgres
import (
"context"
"database/sql"
"github.com/code-payments/code-server/pkg/database/query"
"github.com/code-payments/code-server/pkg/code/data/nonce"
"github.com/jmoiron/sqlx"
)
type store struct {
db *sqlx.DB
}
func New(db *sql.DB) nonce.Store {
return &store{
db: sqlx.NewDb(db, "pgx"),
}
}
// Count returns the total count of nonce accounts.
func (s *store) Count(ctx context.Context) (uint64, error) {
return dbGetCount(ctx, s.db)
}
// Count returns the total count of nonce accounts by state
func (s *store) CountByState(ctx context.Context, state nonce.State) (uint64, error) {
return dbGetCountByState(ctx, s.db, state)
}
// CountByStateAndPurpose returns the total count of nonce accounts in the provided
// state and use case
func (s *store) CountByStateAndPurpose(ctx context.Context, state nonce.State, purpose nonce.Purpose) (uint64, error) {
return dbGetCountByStateAndPurpose(ctx, s.db, state, purpose)
}
// Put saves nonce metadata to the store.
func (s *store) Save(ctx context.Context, record *nonce.Record) error {
obj, err := toNonceModel(record)
if err != nil {
return err
}
err = obj.dbSave(ctx, s.db)
if err != nil {
return err
}
res := fromNonceModel(obj)
res.CopyTo(record)
return nil
}
// Get finds the nonce record for a given address.
//
// Returns ErrNotFound if no record is found.
func (s *store) Get(ctx context.Context, address string) (*nonce.Record, error) {
obj, err := dbGetNonce(ctx, s.db, address)
if err != nil {
return nil, err
}
return fromNonceModel(obj), nil
}
// GetAllByState returns nonce records in the store for a given
// confirmation state.
//
// Returns ErrNotFound if no records are found.
func (s *store) GetAllByState(ctx context.Context, state nonce.State, cursor query.Cursor, limit uint64, direction query.Ordering) ([]*nonce.Record, error) {
models, err := dbGetAllByState(ctx, s.db, state, cursor, limit, direction)
if err != nil {
return nil, err
}
nonces := make([]*nonce.Record, len(models))
for i, model := range models {
nonces[i] = fromNonceModel(model)
}
return nonces, nil
}
// GetRandomAvailableByPurpose gets a random available nonce for a purpose.
//
// Returns ErrNotFound if no records are found.
func (s *store) GetRandomAvailableByPurpose(ctx context.Context, purpose nonce.Purpose) (*nonce.Record, error) {
model, err := dbGetRandomAvailableByPurpose(ctx, s.db, purpose)
if err != nil {
return nil, err
}
return fromNonceModel(model), nil
}