This repository has been archived by the owner on Aug 28, 2023. It is now read-only.
/
transaction.go
120 lines (108 loc) · 2.43 KB
/
transaction.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
package dgraph
import (
"context"
"encoding/json"
"github.com/dgraph-io/dgo"
"github.com/dgraph-io/dgo/protos/api"
"github.com/pkg/errors"
strerr "github.com/romshark/dgraph_graphql_go/store/errors"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
type transaction interface {
Query(
ctx context.Context,
query string,
res interface{},
) error
QueryVars(
ctx context.Context,
query string,
vars map[string]string,
res interface{},
) error
Mutation(
ctx context.Context,
mutation *api.Mutation,
) (map[string]string, error)
}
type txn struct {
dgTxn *dgo.Txn
}
func (txn *txn) isCancelErr(err error) bool {
return status.Code(err) == codes.Canceled
}
func (txn *txn) Query(
ctx context.Context,
query string,
res interface{},
) error {
rep, err := txn.dgTxn.Query(ctx, query)
if err != nil {
if txn.isCancelErr(err) {
return strerr.New(strerr.ErrCanceled, "")
}
return errors.Wrap(err, "query")
}
if err := json.Unmarshal(rep.Json, &res); err != nil {
return errors.Wrap(err, "json unmarsh")
}
return nil
}
func (txn *txn) QueryVars(
ctx context.Context,
query string,
vars map[string]string,
res interface{},
) error {
rep, err := txn.dgTxn.QueryWithVars(ctx, query, vars)
if err != nil {
if txn.isCancelErr(err) {
return strerr.New(strerr.ErrCanceled, "")
}
return errors.Wrap(err, "query")
}
if err := json.Unmarshal(rep.Json, &res); err != nil {
return errors.Wrap(err, "json unmarsh")
}
return nil
}
func (txn *txn) Mutation(
ctx context.Context,
mutation *api.Mutation,
) (map[string]string, error) {
assigned, err := txn.dgTxn.Mutate(ctx, mutation)
if err != nil {
if txn.isCancelErr(err) {
return nil, strerr.New(strerr.ErrCanceled, "")
}
return nil, errors.Wrap(err, "mutation")
}
return assigned.Uids, nil
}
func (str *impl) txn(terr *error) (transaction, func()) {
// Ensure the database is connected
if err := str.ensureActive(); err != nil {
*terr = err
return nil, nil
}
// Create a new transaction and the closure functor
dgTxn := str.db.NewTxn()
txn := &txn{
dgTxn: dgTxn,
}
return txn, func() {
ctx := context.Background()
if *terr != nil {
// Rollback transaction
if rlbErr := dgTxn.Discard(ctx); rlbErr != nil {
*terr = errors.Wrapf(rlbErr, "rollback after: %s", *terr)
}
} else {
// Commit transaction
if commitErr := dgTxn.Commit(ctx); commitErr != nil {
*terr = errors.Wrap(commitErr, "commit")
}
}
}
}