github.com/MetalBlockchain/metalgo@v1.11.9/x/archivedb/reader.go (about)

     1  // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved.
     2  // See the file LICENSE for licensing terms.
     3  
     4  package archivedb
     5  
     6  import "github.com/MetalBlockchain/metalgo/database"
     7  
     8  var _ database.KeyValueReader = (*Reader)(nil)
     9  
    10  type Reader struct {
    11  	db     *Database
    12  	height uint64
    13  }
    14  
    15  func (r *Reader) Has(key []byte) (bool, error) {
    16  	_, err := r.Get(key)
    17  	if err == database.ErrNotFound {
    18  		return false, nil
    19  	}
    20  	return true, err
    21  }
    22  
    23  func (r *Reader) Get(key []byte) ([]byte, error) {
    24  	value, _, exists, err := r.GetEntry(key)
    25  	if err != nil {
    26  		return nil, err
    27  	}
    28  	if exists {
    29  		return value, nil
    30  	}
    31  	return value, database.ErrNotFound
    32  }
    33  
    34  // GetEntry retrieves the value of the provided key, the height it was last
    35  // modified at, and a boolean to indicate if the last modification was an
    36  // insertion. If the key has never been modified, ErrNotFound will be returned.
    37  func (r *Reader) GetEntry(key []byte) ([]byte, uint64, bool, error) {
    38  	it := r.db.db.NewIteratorWithStartAndPrefix(newDBKeyFromUser(key, r.height))
    39  	defer it.Release()
    40  
    41  	next := it.Next()
    42  	if err := it.Error(); err != nil {
    43  		return nil, 0, false, err
    44  	}
    45  
    46  	// There is no available key with the requested prefix
    47  	if !next {
    48  		return nil, 0, false, database.ErrNotFound
    49  	}
    50  
    51  	_, height, err := parseDBKeyFromUser(it.Key())
    52  	if err != nil {
    53  		return nil, 0, false, err
    54  	}
    55  
    56  	value, exists := parseDBValue(it.Value())
    57  	if !exists {
    58  		return nil, height, false, nil
    59  	}
    60  	return value, height, true, nil
    61  }