package repository import ( "context" "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgxpool" e "mic-wallet/server/repository/entities" ) const ( AddBlockSql = `INSERT INTO blocks (id, hash, prev_hash, started_at, finished_at) VALUES ($1, $2, $3, $4, $5)` SetBlockFinishedSql = `UPDATE blocks SET hash = $1 finished_at = $2 WHERE id = $3` GetBlockSql = `SELECT * FROM blocks WHERE id = $1` GetBlockByHashSql = `SELECT * FROM blocks WHERE hash = $1` GetLastFinishedBlockSql = `SELECT * FROM blocks ORDER BY finished_at DESC LIMIT 1` ) type BlocksRepository struct { IBlocksRepository DB *pgxpool.Pool } func ScanBlockRow(row pgx.Row) (block *e.Block, err error) { block = &e.Block{} return block, row.Scan(&block.Id, &block.Hash, &block.PrevHash, &block.StartedAt, &block.FinishedAt) } func (repo BlocksRepository) NewBLock(ctx context.Context, opts e.NewBlockOpts) (blockID int64, err error) { return blockID, repo.DB.QueryRow(ctx, AddBlockSql, opts.Id, opts.Hash, opts.PrevHash, opts.StartedAt, opts.FinishedAt).Scan(&blockID) } func (repo BlocksRepository) FinishBlock(ctx context.Context, opts e.BlockFinishedOpts) (err error) { _, err = repo.DB.Exec(ctx, SetBlockFinishedSql, opts.Hash, opts.FinishedAt, opts.Id) return err } func (repo BlocksRepository) GetBlock(ctx context.Context, id int64) (block *e.Block, err error) { return ScanBlockRow(repo.DB.QueryRow(ctx, GetBlockSql, id)) } func (repo BlocksRepository) GetBlockByHash(ctx context.Context, hash string) (block *e.Block, err error) { return ScanBlockRow(repo.DB.QueryRow(ctx, GetBlockByHashSql, hash)) } func (repo BlocksRepository) GetLastFinishedBlock(ctx context.Context) (block *e.Block, err error) { return ScanBlockRow(repo.DB.QueryRow(ctx, GetLastFinishedBlockSql)) }