-
Notifications
You must be signed in to change notification settings - Fork 1
/
upsert.go
63 lines (55 loc) · 1.4 KB
/
upsert.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
package quirk
import (
"context"
"errors"
"strings"
"github.com/dgraph-io/dgo/v2"
)
func (c *Client) tryUpsert(ctx context.Context, txn *dgo.Txn, dat *DupleNode) *upsertResponse {
defer txn.Discard(ctx)
// Pass this builder around to other functions for less mem alloc.
var builder strings.Builder
// Query to find if there are pre existing nodes with the unique predicates.
uid, err := queryUID(ctx, txn, &builder, dat)
if err != nil {
return &upsertResponse{err: err}
}
// Check if the given data contains the quirk client predicateKey. If not
// then it is defaulted to "data"
identifier := blankDefault
if dat.Identifier != "" {
identifier = dat.Identifier
}
// If the UID was not found by our query then mutate to add a new node.
var new bool
if uid == "" {
new = true
// Insert new node.
uidMap, err := setNode(ctx, txn, &builder, "_:"+identifier, dat)
if err != nil {
return &upsertResponse{
err: err,
new: new,
}
}
// If the UID could not be found in the map.
if uid = uidMap[identifier]; uid == "" {
return &upsertResponse{
err: errors.New(msgMutationHadNoUID),
new: new,
}
}
} else {
// Update the found node.
_, err = setNode(ctx, txn, &builder, "<"+uid+">", dat)
if err != nil {
return &upsertResponse{
err: err,
new: new,
}
}
}
return &upsertResponse{
err: txn.Commit(ctx), new: new, uid: uid, identifier: identifier,
}
}