-
Notifications
You must be signed in to change notification settings - Fork 67
/
incrementor.go
62 lines (56 loc) · 2.33 KB
/
incrementor.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
package sqlite
// BindIndexStart is the index of the first parameter when using the Stmt.Bind*
// functions.
const BindIndexStart = 1
// BindIncrementor returns an Incrementor that starts on 1, the first index
// used in Stmt.Bind* functions. This is provided as syntactic sugar for
// binding parameter values to a Stmt. It allows for easily changing query
// parameters without manually fixing up the bind indexes, which can be error
// prone. For example,
// stmt := conn.Prep(`INSERT INTO test (a, b, c) VALUES (?, ?, ?);`)
// i := BindIncrementor()
// stmt.BindInt64(i(), a) // i() == 1
// if b > 0 {
// stmt.BindInt64(i(), b) // i() == 2
// } else {
// // Remember to increment the index even if a param is NULL
// stmt.BindNull(i()) // i() == 2
// }
// stmt.BindText(i(), c) // i() == 3
func BindIncrementor() Incrementor {
return NewIncrementor(BindIndexStart)
}
// ColumnIndexStart is the index of the first column when using the
// Stmt.Column* functions.
const ColumnIndexStart = 0
// ColumnIncrementor returns an Incrementor that starts on 0, the first index
// used in Stmt.Column* functions. This is provided as syntactic sugar for
// parsing column values from a Stmt. It allows for easily changing queried
// columns without manually fixing up the column indexes, which can be error
// prone. For example,
// stmt := conn.Prep(`SELECT a, b, c FROM test;`)
// stmt.Step()
// i := ColumnIncrementor()
// a := stmt.ColumnInt64(i()) // i() == 1
// b := stmt.ColumnInt64(i()) // i() == 2
// c := stmt.ColumnText(i()) // i() == 3
func ColumnIncrementor() Incrementor {
return NewIncrementor(ColumnIndexStart)
}
// NewIncrementor returns an Incrementor that starts on start.
func NewIncrementor(start int) Incrementor {
return func() int {
start++
return start - 1
}
}
// Incrementor is a closure around a value that returns and increments the
// value on each call. For example, the boolean statments in the following code
// snippet would all be true.
// i := NewIncrementor(3)
// i() == 3
// i() == 4
// i() == 5
// This is provided as syntactic sugar for dealing with bind param and column
// indexes. See BindIncrementor and ColumnIncrementor for small examples.
type Incrementor func() int