Skip to content

Commit e90144c

Browse files
committed
feat(keytransform): support transction feature
1 parent bee84ce commit e90144c

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed

keytransform/keytransform.go

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package keytransform
22

33
import (
44
"context"
5+
"fmt"
56

67
ds "github.com/ipfs/go-datastore"
78
dsq "github.com/ipfs/go-datastore/query"
@@ -31,6 +32,7 @@ type Datastore struct {
3132

3233
var _ ds.Datastore = (*Datastore)(nil)
3334
var _ ds.Batching = (*Datastore)(nil)
35+
var _ ds.TxnDatastore = (*Datastore)(nil)
3436
var _ ds.Shim = (*Datastore)(nil)
3537
var _ ds.PersistentDatastore = (*Datastore)(nil)
3638
var _ ds.CheckedDatastore = (*Datastore)(nil)
@@ -224,6 +226,23 @@ func (d *Datastore) Batch(ctx context.Context) (ds.Batch, error) {
224226
}, nil
225227
}
226228

229+
func (d *Datastore) NewTransaction(ctx context.Context, readOnly bool) (ds.Txn, error) {
230+
tds, ok := d.child.(ds.TxnDatastore)
231+
if !ok {
232+
return nil, fmt.Errorf("txn not supported")
233+
}
234+
235+
childTxn, err := tds.NewTransaction(ctx, readOnly)
236+
if err != nil {
237+
return nil, err
238+
}
239+
240+
return &transformTxn{
241+
dst: childTxn,
242+
f: d.ConvertKey,
243+
}, nil
244+
}
245+
227246
type transformBatch struct {
228247
dst ds.Batch
229248

@@ -244,6 +263,47 @@ func (t *transformBatch) Commit(ctx context.Context) error {
244263
return t.dst.Commit(ctx)
245264
}
246265

266+
type transformTxn struct {
267+
ds *Datastore
268+
dst ds.Txn
269+
270+
f KeyMapping
271+
}
272+
273+
var _ ds.Txn = (*transformTxn)(nil)
274+
275+
func (t *transformTxn) Put(ctx context.Context, key ds.Key, val []byte) error {
276+
return t.dst.Put(ctx, t.f(key), val)
277+
}
278+
279+
func (t *transformTxn) Delete(ctx context.Context, key ds.Key) error {
280+
return t.dst.Delete(ctx, t.f(key))
281+
}
282+
283+
func (t *transformTxn) Commit(ctx context.Context) error {
284+
return t.dst.Commit(ctx)
285+
}
286+
287+
func (t *transformTxn) Get(ctx context.Context, key ds.Key) (value []byte, err error) {
288+
return t.dst.Get(ctx, t.f(key))
289+
}
290+
291+
func (t *transformTxn) Has(ctx context.Context, key ds.Key) (exists bool, err error) {
292+
return t.dst.Has(ctx, t.f(key))
293+
}
294+
295+
func (t *transformTxn) GetSize(ctx context.Context, key ds.Key) (size int, err error) {
296+
return t.dst.GetSize(ctx, t.f(key))
297+
}
298+
299+
func (t *transformTxn) Query(ctx context.Context, q dsq.Query) (dsq.Results, error) {
300+
return t.ds.Query(ctx, q)
301+
}
302+
303+
func (t *transformTxn) Discard(ctx context.Context) {
304+
t.dst.Discard(ctx)
305+
}
306+
247307
func (d *Datastore) Check(ctx context.Context) error {
248308
if c, ok := d.child.(ds.CheckedDatastore); ok {
249309
return c.Check(ctx)

0 commit comments

Comments
 (0)