Debian Codegraph @

database/etcddb/transaction.go

raw
1 package etcddb
2
3 import (
4 "github.com/aptly-dev/aptly/database"
5 clientv3 "go.etcd.io/etcd/client/v3"
6 )
7
8 type transaction struct {
9 s *EtcDStorage
10 tmpdb database.Storage
11 ops []clientv3.Op
12 }
13
14 // Get implements database.Reader interface.
15 func (t *transaction) Get(key []byte) (value []byte, err error) {
16 value, err = t.tmpdb.Get(key)
17 // if not found, search main db
18 if err != nil {
19 value, err = t.s.Get(key)
20 }
21 return
22 }
23
24 // Put implements database.Writer interface.
25 func (t *transaction) Put(key, value []byte) (err error) {
26 err = t.tmpdb.Put(key, value)
27 if err != nil {
28 return
29 }
30 t.ops = append(t.ops, clientv3.OpPut(string(key), string(value)))
31 return
32 }
33
34 // Delete implements database.Writer interface.
35 func (t *transaction) Delete(key []byte) (err error) {
36 err = t.tmpdb.Delete(key)
37 if err != nil {
38 return
39 }
40 t.ops = append(t.ops, clientv3.OpDelete(string(key)))
41 return
42 }
43
44 func (t *transaction) Commit() (err error) {
45 kv := clientv3.NewKV(t.s.db)
46
47 batchSize := 128
48 for i := 0; i < len(t.ops); i += batchSize {
49 txn := kv.Txn(Ctx)
50 end := i + batchSize
51 if end > len(t.ops) {
52 end = len(t.ops)
53 }
54
55 batch := t.ops[i:end]
56 txn.Then(batch...)
57 _, err = txn.Commit()
58 if err != nil {
59 panic(err)
60 }
61 }
62 t.ops = []clientv3.Op{}
63
64 return
65 }
66
67 // Discard is safe to call after Commit(), it would be no-op
68 func (t *transaction) Discard() {
69 t.ops = []clientv3.Op{}
70 _ = t.tmpdb.Drop()
71 }
72
73 // transaction should implement database.Transaction
74 var _ database.Transaction = &transaction{}