-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample_test.go
More file actions
238 lines (198 loc) · 4.61 KB
/
Copy pathexample_test.go
File metadata and controls
238 lines (198 loc) · 4.61 KB
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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
package sqlz_test
import (
"context"
"database/sql"
"fmt"
"log"
"strings"
"time"
"github.com/rfberaldo/sqlz"
)
var (
db *sqlz.DB
ctx = context.Background()
)
func ExampleNew() {
pool, err := sql.Open("sqlite3", ":memory:")
if err != nil {
log.Fatal(err)
}
db := sqlz.New("sqlite3", pool, nil)
_, err = db.Exec(ctx, "CREATE TABLE user (id INT PRIMARY KEY, name TEXT")
if err != nil {
log.Fatal(err)
}
}
func ExampleNew_options() {
pool, err := sql.Open("sqlite3", ":memory:")
if err != nil {
log.Fatal(err)
}
// use sqlz.Options as third parameter
db := sqlz.New("sqlite3", pool, &sqlz.Options{
Bind: sqlz.BindDollar,
StructTag: "json",
FieldNameTransformer: strings.ToLower,
IgnoreMissingFields: true,
})
_, err = db.Exec(ctx, "CREATE TABLE user (id INT PRIMARY KEY, name TEXT")
if err != nil {
log.Fatal(err)
}
}
func ExampleDB_Query() {
var names []string
err := db.Query(ctx, "SELECT name FROM user WHERE age > ?", 27).Scan(&names)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v", names)
}
func ExampleDB_Query_named() {
type Params struct {
Age int
}
var names []string
params := Params{Age: 27} // or map[string]any{"age": 27}
err := db.
Query(ctx, "SELECT name FROM user WHERE age > :age", params).
Scan(&names)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v", names)
}
func ExampleDB_Query_in_clause() {
var names []string
ages := []int{27, 28, 29}
err := db.
Query(ctx, "SELECT name FROM user WHERE age IN (?)", ages).
Scan(&names)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v", names)
}
func ExampleDB_Query_named_in_clause() {
type Params struct {
Ages []int
}
var names []string
params := Params{Ages: []int{27, 28, 29}}
err := db.
Query(ctx, "SELECT name FROM user WHERE age IN (:ages)", params).
Scan(&names)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v", names)
}
func ExampleDB_QueryRow() {
type User struct {
Username string
CreatedAt time.Time
}
id := 42
var user User
err := db.
QueryRow(ctx, "SELECT username, created_at FROM user WHERE id = ?", id).
Scan(&user)
switch {
case sqlz.IsNotFound(err):
log.Printf("no user with id %d\n", id)
case err != nil:
log.Fatalf("query error: %v\n", err)
default:
log.Printf("username is %q, account created on %s\n", user.Username, user.CreatedAt)
}
}
func ExampleDB_Exec() {
id := 42
result, err := db.Exec(ctx, "UPDATE balances SET balance = balance + 10 WHERE user_id = ?", id)
if err != nil {
log.Fatal(err)
}
rows, err := result.RowsAffected()
if err != nil {
log.Fatal(err)
}
if rows != 1 {
log.Fatalf("expected to affect 1 row, affected %d", rows)
}
}
func ExampleDB_Exec_batch_insert() {
type User struct {
Username string
CreatedAt time.Time
}
users := []User{
{"john", time.Now()},
{"alice", time.Now()},
{"rob", time.Now()},
{"brian", time.Now()},
}
_, err := db.Exec(ctx, "INSERT INTO user (username, created_at) VALUES (:username, :created_at)", users)
if err != nil {
log.Fatal(err)
}
}
func ExampleDB_Begin() {
tx, err := db.Begin(ctx)
if err != nil {
log.Fatal(err)
}
// Rollback will be ignored if tx has been committed later in the function,
// remember to return early if there is an error.
defer tx.Rollback()
args := map[string]any{"status": "paid", "id": 37}
_, err = tx.Exec(ctx, "UPDATE user SET status = :status WHERE id = :id", args)
if err != nil {
log.Fatal(err)
return
}
if err := tx.Commit(); err != nil {
log.Fatalf("unable to commit: %v", err)
}
}
func ExampleDB_BeginTx() {
tx, err := db.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelSerializable})
if err != nil {
log.Fatal(err)
}
// Rollback will be ignored if tx has been committed later in the function,
// remember to return early if there is an error.
defer tx.Rollback()
args := map[string]any{"status": "paid", "id": 37}
_, err = tx.Exec(ctx, "UPDATE user SET status = :status WHERE id = :id", args)
if err != nil {
log.Fatal(err)
return
}
if err := tx.Commit(); err != nil {
log.Fatalf("unable to commit: %v", err)
}
}
func ExampleDB_Pool() {
db.Pool().SetMaxOpenConns(10)
db.Pool().SetMaxIdleConns(4)
}
func ExampleScanner_ForEach() {
// logs might have millions of rows, we don't want to allocate all at once
scanner := db.Query(ctx, "SELECT * FROM logs")
type Log struct {
Id int
// etc.
}
// ForEach arg is a callback function that you can use to scan a single row
err := scanner.ForEach(func(scan sqlz.ScanFunc) error {
var log Log
if err := scan(&log); err != nil {
return err
}
// do stuff with each row
return nil
})
if err != nil {
log.Fatal(err)
}
}