-
Notifications
You must be signed in to change notification settings - Fork 0
/
example_placeholders_test.go
63 lines (53 loc) · 1.2 KB
/
example_placeholders_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
package pg_test
import (
"fmt"
"gopkg.in/pg.v5"
)
type Params struct {
X int
Y int
}
func (p *Params) Sum() int {
return p.X + p.Y
}
// go-pg recognizes placeholders (`?`) in queries and replaces them
// with parameters when queries are executed. Parameters are escaped
// before replacing according to PostgreSQL rules. Specifically:
// - all parameters are properly quoted against SQL injections;
// - null byte is removed;
// - JSON/JSONB gets `\u0000` escaped as `\\u0000`.
func Example_placeholders() {
var num int
// Simple params.
_, err := db.Query(pg.Scan(&num), "SELECT ?", 42)
if err != nil {
panic(err)
}
fmt.Println("simple:", num)
// Indexed params.
_, err = db.Query(pg.Scan(&num), "SELECT ?0 + ?0", 1)
if err != nil {
panic(err)
}
fmt.Println("indexed:", num)
// Named params.
params := &Params{
X: 1,
Y: 1,
}
_, err = db.Query(pg.Scan(&num), "SELECT ?x + ?y + ?Sum", params)
if err != nil {
panic(err)
}
fmt.Println("named:", num)
// Global params.
_, err = db.WithParam("z", 1).Query(pg.Scan(&num), "SELECT ?x + ?y + ?z", params)
if err != nil {
panic(err)
}
fmt.Println("global:", num)
// Output: simple: 42
// indexed: 2
// named: 4
// global: 3
}