forked from rethinkdb/rethinkdb-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexample_query_select_test.go
101 lines (84 loc) · 2.49 KB
/
example_query_select_test.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
package gorethink_test
import (
"fmt"
"log"
r "github.com/dancannon/gorethink"
)
func Example_Get() {
type Person struct {
Id string `gorethink:"id, omitempty"`
FirstName string `gorethink:"first_name"`
LastName string `gorethink:"last_name"`
Gender string `gorethink:"gender"`
}
sess, err := r.Connect(r.ConnectOpts{
Address: url,
AuthKey: authKey,
})
if err != nil {
log.Fatalf("Error connecting to DB: %s", err)
}
// Setup table
r.Db("test").TableDrop("table").Run(sess)
r.Db("test").TableCreate("table").Run(sess)
r.Db("test").Table("table").Insert(Person{"1", "John", "Smith", "M"}).Run(sess)
// Fetch the row from the database
res, err := r.Db("test").Table("table").Get("1").Run(sess)
if err != nil {
log.Fatalf("Error finding person: %s", err)
}
if res.IsNil() {
log.Fatalf("Person not found")
}
// Scan query result into the person variable
var person Person
err = res.One(&person)
if err != nil {
log.Fatalf("Error scanning database result: %s", err)
}
fmt.Printf("%s %s (%s)", person.FirstName, person.LastName, person.Gender)
// Output:
// John Smith (M)
}
func Example_GetAll_Compound() {
type Person struct {
Id string `gorethink:"id, omitempty"`
FirstName string `gorethink:"first_name"`
LastName string `gorethink:"last_name"`
Gender string `gorethink:"gender"`
}
sess, err := r.Connect(r.ConnectOpts{
Address: url,
AuthKey: authKey,
})
if err != nil {
log.Fatalf("Error connecting to DB: %s", err)
}
// Setup table
r.Db("test").TableDrop("table").Run(sess)
r.Db("test").TableCreate("table").Run(sess)
r.Db("test").Table("table").Insert(Person{"1", "John", "Smith", "M"}).Run(sess)
r.Db("test").Table("table").IndexCreateFunc("full_name", func(row r.Term) interface{} {
return []interface{}{row.Field("first_name"), row.Field("last_name")}
}).Run(sess)
r.Db("test").Table("table").IndexWait().Run(sess)
// Fetch the row from the database
res, err := r.Db("test").Table("table").GetAllByIndex("full_name", []interface{}{"John", "Smith"}).Run(sess)
if err != nil {
log.Fatalf("Error finding person: %s", err)
}
if res.IsNil() {
log.Fatalf("Person not found")
}
// Scan query result into the person variable
var person Person
err = res.One(&person)
if err == r.ErrEmptyResult {
log.Fatalf("Person not found")
} else if err != nil {
log.Fatalf("Error scanning database result: %s", err)
}
fmt.Printf("%s %s (%s)", person.FirstName, person.LastName, person.Gender)
// Output:
// John Smith (M)
}