forked from lukashes/pg
/
example_test.go
140 lines (116 loc) · 2.54 KB
/
example_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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
package pg_test
import (
"bytes"
"fmt"
"strings"
"github.com/lukashes/pg"
)
var db *pg.DB
func init() {
db = pg.Connect(&pg.Options{
User: "postgres",
})
}
func ExampleConnect() {
db := pg.Connect(&pg.Options{
User: "postgres",
})
err := db.Close()
fmt.Println(err)
// Output: <nil>
}
func ExampleDB_QueryOne() {
var user struct {
Name string
}
res, err := db.QueryOne(&user, `
WITH users (name) AS (VALUES (?))
SELECT * FROM users
`, "admin")
fmt.Println(res.Affected(), err)
fmt.Println(user)
// Output: 1 <nil>
// {admin}
}
func ExampleDB_Exec() {
res, err := db.Exec("CREATE TEMP TABLE test()")
fmt.Println(res.Affected(), err)
// Output: 0 <nil>
}
func ExampleLoadInto() {
var s1, s2 string
_, err := db.QueryOne(pg.LoadInto(&s1, &s2), "SELECT ?, ?", "foo", "bar")
fmt.Println(s1, s2, err)
// Output: foo bar <nil>
}
func ExampleListener() {
ln, _ := db.Listen("mychan")
done := make(chan struct{})
go func() {
channel, payload, err := ln.Receive()
fmt.Printf("%s %q %v", channel, payload, err)
done <- struct{}{}
}()
_, _ = db.Exec("NOTIFY mychan, ?", "hello world")
<-done
// Output: mychan "hello world" <nil>
}
func ExampleDB_Begin() {
tx, err := db.Begin()
if err != nil {
panic(err)
}
_, err = tx.Exec("CREATE TEMP TABLE test()")
if err != nil {
panic(err)
}
err = tx.Rollback()
if err != nil {
panic(err)
}
_, err = db.Exec("SELECT * FROM test")
fmt.Println(err)
// Output: ERROR #42P01 relation "test" does not exist:
}
func ExampleDB_Prepare() {
stmt, err := db.Prepare("SELECT $1::text, $2::text")
if err != nil {
panic(err)
}
var s1, s2 string
_, err = stmt.QueryOne(pg.LoadInto(&s1, &s2), "foo", "bar")
fmt.Println(s1, s2, err)
// Output: foo bar <nil>
}
func ExampleInts() {
var nums pg.Ints
_, err := db.Query(&nums, "SELECT generate_series(0, 10)")
fmt.Println(nums, err)
// Output: [0 1 2 3 4 5 6 7 8 9 10] <nil>
}
func ExampleStrings() {
var strs pg.Strings
_, err := db.Query(
&strs, "WITH users AS (VALUES ('foo'), ('bar')) SELECT * FROM users")
fmt.Println(strs, err)
// Output: [foo bar] <nil>
}
func ExampleDB_CopyFrom() {
_, err := db.Exec("CREATE TEMP TABLE words(word text, len int)")
if err != nil {
panic(err)
}
r := strings.NewReader("hello,5\nfoo,3\n")
_, err = db.CopyFrom(r, "COPY words FROM STDIN WITH CSV")
if err != nil {
panic(err)
}
buf := &bytes.Buffer{}
_, err = db.CopyTo(&NopWriteCloser{buf}, "COPY words TO STDOUT WITH CSV")
if err != nil {
panic(err)
}
fmt.Println(buf.String())
// Output: hello,5
// foo,3
}