-
-
Notifications
You must be signed in to change notification settings - Fork 404
/
example_placeholders_test.go
82 lines (71 loc) · 1.8 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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package pg_test
import (
"fmt"
"github.com/go-pg/pg/v10"
)
type Params struct {
X int
Y int
}
func (p *Params) Sum() int {
return p.X + p.Y
}
// go-pg recognizes `?` in queries as placeholders and replaces them
// with parameters when queries are executed. `?` can be escaped with backslash.
// 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 := pgdb.Query(pg.Scan(&num), "SELECT ?", 42)
if err != nil {
panic(err)
}
fmt.Println("simple:", num)
// Indexed params.
_, err = pgdb.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 = pgdb.Query(pg.Scan(&num), "SELECT ?x + ?y + ?Sum", params)
if err != nil {
panic(err)
}
fmt.Println("named:", num)
// Global params.
_, err = pgdb.WithParam("z", 1).Query(pg.Scan(&num), "SELECT ?x + ?y + ?z", params)
if err != nil {
panic(err)
}
fmt.Println("global:", num)
// Model params.
var tableName, tableAlias, tableColumns, columns string
_, err = pgdb.Model(&Params{}).Query(
pg.Scan(&tableName, &tableAlias, &tableColumns, &columns),
"SELECT '?TableName', '?TableAlias', '?TableColumns', '?Columns'",
)
if err != nil {
panic(err)
}
fmt.Println("table name:", tableName)
fmt.Println("table alias:", tableAlias)
fmt.Println("table columns:", tableColumns)
fmt.Println("columns:", columns)
// Output: simple: 42
// indexed: 2
// named: 4
// global: 3
// table name: "params"
// table alias: "params"
// table columns: "params"."x", "params"."y"
// columns: "x", "y"
}