-
Notifications
You must be signed in to change notification settings - Fork 0
/
txn.go
64 lines (59 loc) · 1.33 KB
/
txn.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
package dgraph
import (
"context"
"encoding/json"
"fmt"
"github.com/dgraph-io/dgo/v210"
)
type Txn struct {
*dgo.Txn
}
// Schema 获取dgraph所有谓词和类型
func (d *Txn) Schema() (Schema, error) {
resp, err := d.Txn.Query(context.Background(), `schema{}`)
if err != nil {
return Schema{}, err
}
r := Schema{}
err = json.Unmarshal(resp.Json, &r)
if err != nil {
return Schema{}, err
}
r = r.SkipSysSchema()
return r, err
}
// SchemaPred 查找特定谓词结构,如果不存在则报错
func (d *Txn) SchemaPred(name string) (SchemaPred, error) {
var res Schema
q := fmt.Sprintf(`schema(pred: %s){}`, name)
resp, err := d.Txn.Query(context.Background(), q)
if err != nil {
return SchemaPred{}, err
}
err = json.Unmarshal(resp.Json, &res)
if err != nil {
return SchemaPred{}, err
}
if len(res.Preds) == 0 {
return SchemaPred{}, nil
}
p := res.Preds[0]
return p, nil
}
// SchemaType 查找特定类型,如果不存在则报错
func (d *Txn) SchemaType(name string) (SchemaType, error) {
var res Schema
resp, err := d.Txn.Query(context.Background(), fmt.Sprintf(`schema(type: %s){}`, name))
if err != nil {
return SchemaType{}, err
}
err = json.Unmarshal(resp.Json, &res)
if err != nil {
return SchemaType{}, err
}
if len(res.Types) == 0 {
return SchemaType{}, nil
}
p := res.Types[0]
return p, nil
}