-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample_test.go
More file actions
64 lines (57 loc) · 1.13 KB
/
example_test.go
File metadata and controls
64 lines (57 loc) · 1.13 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
package sqlfunc_test
import (
"context"
"database/sql"
"log"
"github.com/deadblue/sqlfunc"
)
type (
QueryParams struct {
UserId string
Status int
}
UserResult struct {
UserId string
FirstName string
// sql.NullXXX types are supported.
LastName sql.NullString
// Mapping "sex" column to [Gender] field.
Gender int `sql:"sex"`
}
)
func Example() {
// Make SQL function
queryUser, err := sqlfunc.MakeQueryFunc[QueryParams, UserResult](
"SELECT user_id, first_name, last_name, sex",
"FROM tbl_user",
"WHERE user_id = {{ .UserID }} AND status = {{ .Status }}",
)
if err != nil {
panic(err)
}
// Connect to database
db, err := sql.Open("driver", "DSN")
if err != nil {
panic(err)
}
// Put DB to context
ctx := sqlfunc.NewContext(context.TODO(), db)
// Execute query
result, err := queryUser(ctx, QueryParams{
UserId: "123",
Status: 1,
})
if err != nil {
panic(err)
}
if !result.Valid {
return
}
user := result.V
// Process result
if user.LastName.Valid {
log.Printf("Found user: %s-%s", user.FirstName, user.LastName.String)
} else {
log.Printf("Found user: %s", user.FirstName)
}
}