Skip to content

Commit

Permalink
feat: improve and refactor blocktx store queries
Browse files Browse the repository at this point in the history
  • Loading branch information
kuba-4chain committed Aug 30, 2024
1 parent 754de23 commit 9cbc985
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 111 deletions.
41 changes: 30 additions & 11 deletions internal/blocktx/store/postgresql/get_block.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,25 +11,44 @@ import (
)

func (p *PostgreSQL) GetBlock(ctx context.Context, hash *chainhash.Hash) (*blocktx_api.Block, error) {
predicate := "WHERE hash = $1"

return p.queryBlockByPredicate(ctx, predicate, hash[:])
}

func (p *PostgreSQL) GetBlockByHeight(ctx context.Context, height uint64, status blocktx_api.Status) (*blocktx_api.Block, error) {
predicate := "WHERE height = $1 AND status = $2"

return p.queryBlockByPredicate(ctx, predicate, height, status)
}

func (p *PostgreSQL) GetChainTip(ctx context.Context) (*blocktx_api.Block, error) {
predicate := "WHERE height = (SELECT MAX(height) FROM blocktx.blocks blks WHERE blks.status = $1)"

return p.queryBlockByPredicate(ctx, predicate, blocktx_api.Status_LONGEST)
}

func (p *PostgreSQL) queryBlockByPredicate(ctx context.Context, predicate string, predicateParams ...any) (*blocktx_api.Block, error) {
q := `
SELECT
b.hash,
b.prevhash,
b.merkleroot,
b.height,
b.processed_at,
b.orphanedyn,
b.status,
b.chainwork
FROM blocktx.blocks b
WHERE b.hash = $1
hash
,prevhash
,merkleroot
,height
,processed_at
,orphanedyn
,status
,chainwork
FROM blocktx.blocks
`

q += " " + predicate

var block blocktx_api.Block

var processed_at sql.NullString

if err := p.db.QueryRowContext(ctx, q, hash[:]).Scan(
if err := p.db.QueryRowContext(ctx, q, predicateParams...).Scan(
&block.Hash,
&block.PreviousHash,
&block.MerkleRoot,
Expand Down
50 changes: 0 additions & 50 deletions internal/blocktx/store/postgresql/get_block_by_height.go

This file was deleted.

50 changes: 0 additions & 50 deletions internal/blocktx/store/postgresql/get_chain_tip.go

This file was deleted.

0 comments on commit 9cbc985

Please sign in to comment.