-
Notifications
You must be signed in to change notification settings - Fork 8
/
example_test.go
65 lines (57 loc) · 1.89 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
package sqlf_test
import (
"database/sql"
"fmt"
"log"
"github.com/keegancsmith/sqlf"
)
func Example() {
// This is an example which shows off embedding SQL, which simplifies building
// complicated SQL queries
name := "John"
age, offset := 27, 100
where := sqlf.Sprintf("name=%s AND age=%d", name, age)
limit := sqlf.Sprintf("%d OFFSET %d", 10, offset)
q := sqlf.Sprintf("SELECT name FROM users WHERE %s LIMIT %s", where, limit)
fmt.Println(q.Query(sqlf.PostgresBindVar))
fmt.Println(q.Args())
// Output: SELECT name FROM users WHERE name=$1 AND age=$2 LIMIT $3 OFFSET $4
// [John 27 10 100]
}
func ExampleJoin() {
// Our inputs
minQuantity := 100
nameFilters := []string{"apple", "orange", "coffee"}
var conds []*sqlf.Query
for _, filter := range nameFilters {
conds = append(conds, sqlf.Sprintf("name LIKE %s", "%"+filter+"%"))
}
subQuery := sqlf.Sprintf("SELECT product_id FROM order_item WHERE quantity > %d", minQuantity)
q := sqlf.Sprintf("SELECT name FROM product WHERE id IN (%s) AND (%s)", subQuery, sqlf.Join(conds, "OR"))
fmt.Println(q.Query(sqlf.PostgresBindVar))
fmt.Println(q.Args())
// Output: SELECT name FROM product WHERE id IN (SELECT product_id FROM order_item WHERE quantity > $1) AND (name LIKE $2 OR name LIKE $3 OR name LIKE $4)
// [100 %apple% %orange% %coffee%]
}
var db *sql.DB
func Example_dbquery() {
age := 27
// The next two lines are the only difference from the dabatabase/sql/db.Query example.
// Original is rows, err := db.Query("SELECT name FROM users WHERE age=?", age)
s := sqlf.Sprintf("SELECT name FROM users WHERE age=%d", age)
rows, err := db.Query(s.Query(sqlf.SimpleBindVar), s.Args()...)
if err != nil {
log.Fatal(err)
}
defer rows.Close()
for rows.Next() {
var name string
if err := rows.Scan(&name); err != nil {
log.Fatal(err)
}
fmt.Printf("%s is %d\n", name, age)
}
if err := rows.Err(); err != nil {
log.Fatal(err)
}
}