-
Notifications
You must be signed in to change notification settings - Fork 23
/
store.go
71 lines (61 loc) · 2 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
package db
import (
"context"
"errors"
"fmt"
"github.com/synapsecns/sanguine/core/dbcommon"
"github.com/synapsecns/sanguine/core/metrics"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
// NewChainListenerStore creates a new transaction store.
func NewChainListenerStore(db *gorm.DB, metrics metrics.Handler) *Store {
return &Store{
db: db,
metrics: metrics,
}
}
// Store is the sqlite store. It extends the base store for sqlite specific queries.
type Store struct {
db *gorm.DB
metrics metrics.Handler
}
// PutLatestBlock upserts the latest block into the database.
func (s Store) PutLatestBlock(ctx context.Context, chainID, height uint64) error {
tx := s.db.WithContext(ctx).Clauses(clause.OnConflict{
Columns: []clause.Column{{Name: chainIDFieldName}},
DoUpdates: clause.AssignmentColumns([]string{chainIDFieldName, blockNumberFieldName}),
}).Create(&LastIndexed{
ChainID: chainID,
BlockNumber: int(height),
})
if tx.Error != nil {
return fmt.Errorf("could not block updated: %w", tx.Error)
}
return nil
}
// LatestBlockForChain gets the latest block for a chain.
func (s Store) LatestBlockForChain(ctx context.Context, chainID uint64) (uint64, error) {
blockWatchModel := LastIndexed{ChainID: chainID}
err := s.db.WithContext(ctx).First(&blockWatchModel).Error
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return 0, ErrNoLatestBlockForChainID
}
return 0, fmt.Errorf("could not fetch latest block: %w", err)
}
return uint64(blockWatchModel.BlockNumber), nil
}
func init() {
namer := dbcommon.NewNamer(GetAllModels())
chainIDFieldName = namer.GetConsistentName("ChainID")
blockNumberFieldName = namer.GetConsistentName("BlockNumber")
}
var (
// chainIDFieldName gets the chain id field name.
chainIDFieldName string
// blockNumberFieldName is the name of the block number field.
blockNumberFieldName string
)
// ErrNoLatestBlockForChainID is returned when no block exists for the chain.
var ErrNoLatestBlockForChainID = errors.New("no latest block for chainId")