tokenbridge-monitor/repository/postgres/logs_cursors.go

53 lines
1.6 KiB
Go
Raw Normal View History

2021-09-19 14:38:56 -07:00
package postgres
import (
"context"
"fmt"
sq "github.com/Masterminds/squirrel"
"github.com/ethereum/go-ethereum/common"
2022-05-22 04:29:01 -07:00
2022-08-28 04:31:28 -07:00
"github.com/omni/tokenbridge-monitor/db"
"github.com/omni/tokenbridge-monitor/entity"
2021-09-19 14:38:56 -07:00
)
2021-10-08 06:57:20 -07:00
type logsCursorsRepo basePostgresRepo
2021-09-19 14:38:56 -07:00
func NewLogsCursorRepo(table string, db *db.DB) entity.LogsCursorsRepo {
2021-10-08 06:57:20 -07:00
return (*logsCursorsRepo)(newBasePostgresRepo(table, db))
2021-09-19 14:38:56 -07:00
}
func (r *logsCursorsRepo) Ensure(ctx context.Context, cursor *entity.LogsCursor) error {
q, args, err := sq.Insert(r.table).
Columns("chain_id", "address", "last_fetched_block", "last_processed_block").
Values(cursor.ChainID, cursor.Address, cursor.LastFetchedBlock, cursor.LastProcessedBlock).
Suffix("ON CONFLICT (chain_id, address) DO UPDATE SET updated_at = NOW(), last_fetched_block = EXCLUDED.last_fetched_block, last_processed_block = EXCLUDED.last_processed_block").
PlaceholderFormat(sq.Dollar).
ToSql()
if err != nil {
return fmt.Errorf("can't build query: %w", err)
}
_, err = r.db.ExecContext(ctx, q, args...)
if err != nil {
return fmt.Errorf("can't insert logs cursor: %w", err)
}
return nil
}
func (r *logsCursorsRepo) GetByChainIDAndAddress(ctx context.Context, chainID string, addr common.Address) (*entity.LogsCursor, error) {
q, args, err := sq.Select("*").
From(r.table).
Where(sq.Eq{"chain_id": chainID, "address": addr}).
PlaceholderFormat(sq.Dollar).
ToSql()
if err != nil {
return nil, fmt.Errorf("can't build query: %w", err)
}
log := new(entity.LogsCursor)
err = r.db.GetContext(ctx, log, q, args...)
if err != nil {
return nil, fmt.Errorf("can't get logs cursor by chain_id and address: %w", err)
}
return log, nil
}