forked from zhihu/norm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
115 lines (102 loc) · 2.48 KB
/
main.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
package main
import (
"time"
"log"
"github.com/zhihu/norm"
"github.com/zhihu/norm/constants"
"github.com/zhihu/norm/dialectors"
"github.com/zhihu/norm/examples"
)
func main() {
dalector := dialectors.MustNewNebulaDialector(dialectors.DialectorConfig{
Addresses: []string{"127.0.0.1:9669"},
Timeout: time.Second * 5,
Space: "test",
Username: "test",
Password: "test",
})
db := norm.MustOpen(dalector, norm.Config{})
// prepare(db)
run(db)
}
func prepare(db *norm.DB) {
// 创建 tag
createSchema := "" +
"CREATE TAG IF NOT EXISTS user(id int, name string);" +
"CREATE TAG IF NOT EXISTS answer(id int, vote_up_cnt int);" +
"CREATE EDGE IF NOT EXISTS answer_vote_up(vote_up_cnt int, created timestamp);"
_, err := db.Execute(createSchema)
if err != nil {
log.Fatalf("exec %s error: %v", createSchema, err)
panic(err)
}
}
func run(db *norm.DB) {
insert(db)
match(db)
}
func insert(db *norm.DB) {
insertVertex(db)
insertEdge(db)
}
func insertVertex(db *norm.DB) {
user := &examples.User{
VModel: norm.VModel{
Vid: "user_101",
Policy: constants.PolicyHash,
},
ID: 101,
Created: time.Now().Unix(),
}
err := db.Debug().InsertVertex(user)
if err != nil {
log.Fatalf("insert %+v error: %v", user, err)
panic(err)
}
}
func insertEdge(db *norm.DB) {
vote := &examples.AnswerVoteUp{
EModel: norm.EModel{
Src: "user_101",
SrcPolicy: constants.PolicyHash,
Dst: "answer_102",
DstPolicy: constants.PolicyHash,
},
VoteUpCnt: 101,
Created: time.Now().Unix(),
}
err := db.Debug().InsertEdge(vote)
if err != nil {
log.Fatalf("insert %+v error: %v", vote, err)
panic(err)
}
}
func match(db *norm.DB) {
matchSingle(db)
matchMulti(db)
}
func matchSingle(db *norm.DB) {
nsql := "match(v:user) where id(v)==hash('user_101') return v.id as id,v.created as created"
user := examples.User{}
err := db.Debug().ExecuteAndParse(nsql, &user)
if err != nil {
log.Fatalf("exec %s error: %v", nsql, err)
panic(err)
}
log.Printf("%+v", user)
}
func matchMulti(db *norm.DB) {
nsql := "match(v:user) where id(v)==hash('user_101') or id(v)==hash('user_100')" +
" return v.id as id,v.created as created"
users := []examples.User{}
err := db.Debug().ExecuteAndParse(nsql, &users)
if err != nil {
log.Fatalf("exec %s error: %v", nsql, err)
panic(err)
}
log.Printf("%+v", users)
}
// feature support
func chainQuery(db *norm.DB) {
// db.Debug().From(&examples.User{}).Over(&examples.AnswerVoteUp{}).Reversely().Row()
}