unistore: refactor get to return a reader (#107951)

This commit is contained in:
Georges Chaudy
2025-07-11 11:10:19 +02:00
committed by GitHub
parent a314b99589
commit ea0ddb3fc9
7 changed files with 48 additions and 65 deletions
+9 -21
View File
@@ -29,18 +29,12 @@ type ListOptions struct {
Limit int64 // maximum number of results to return. 0 means no limit.
}
// KVObject represents a key-value object
type KVObject struct {
Key string // the key of the object within the section
Value io.ReadCloser // the value of the object
}
type KV interface {
// Keys returns all the keys in the store
Keys(ctx context.Context, section string, opt ListOptions) iter.Seq2[string, error]
// Get retrieves a key-value pair from the store
Get(ctx context.Context, section string, key string) (KVObject, error)
// Get retrieves the value for a key from the store
Get(ctx context.Context, section string, key string) (io.ReadCloser, error)
// Save a new value
Save(ctx context.Context, section string, key string, value io.Reader) error
@@ -67,16 +61,16 @@ func NewBadgerKV(db *badger.DB) *badgerKV {
}
}
func (k *badgerKV) Get(ctx context.Context, section string, key string) (KVObject, error) {
func (k *badgerKV) Get(ctx context.Context, section string, key string) (io.ReadCloser, error) {
if k.db.IsClosed() {
return KVObject{}, fmt.Errorf("database is closed")
return nil, fmt.Errorf("database is closed")
}
txn := k.db.NewTransaction(false)
defer txn.Discard()
if section == "" {
return KVObject{}, fmt.Errorf("section is required")
return nil, fmt.Errorf("section is required")
}
key = section + "/" + key
@@ -84,24 +78,18 @@ func (k *badgerKV) Get(ctx context.Context, section string, key string) (KVObjec
item, err := txn.Get([]byte(key))
if err != nil {
if errors.Is(err, badger.ErrKeyNotFound) {
return KVObject{}, ErrNotFound
return nil, ErrNotFound
}
return KVObject{}, err
}
out := KVObject{
Key: string(item.Key())[len(section)+1:],
return nil, err
}
// Get the value and create a reader from it
value, err := item.ValueCopy(nil)
if err != nil {
return KVObject{}, err
return nil, err
}
out.Value = io.NopCloser(bytes.NewReader(value))
return out, nil
return io.NopCloser(bytes.NewReader(value)), nil
}
func (k *badgerKV) Save(ctx context.Context, section string, key string, value io.Reader) error {