-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
102 lines (87 loc) · 2.17 KB
/
main.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package main
import (
"context"
"database/sql"
"log/slog"
"os"
"time"
"fmt"
"github.com/jmoiron/sqlx"
_ "github.com/lib/pq"
"github.com/stephennancekivell/querypulse"
"github.com/stephennancekivell/querypulse/qslog"
)
func main() {
ctx := context.Background()
// Register the driver wrapping the postgres driver.
driverName, err := querypulse.Register(
"postgres",
querypulse.Options{
OnSuccess: func(ctx context.Context, query string, args []any, duration time.Duration) {
fmt.Printf("OnSuccess: %v %v %v\n", query, args, duration)
},
})
if err != nil {
panic(err)
}
// Connect to database
connStr := "postgresql://test:test@localhost/test?sslmode=disable"
db, err := sql.Open(driverName, connStr)
if err != nil {
panic(err)
}
// execute queries just an you normally would with the *sql.DB interface
rows, err := db.Query("select $1", 100)
if err != nil {
panic(err)
}
defer rows.Close()
// Also works with sqlx.
dbx := sqlx.NewDb(db, "postgres") // sqlx requires the original postgres driver name.
_, err = dbx.QueryContext(ctx, "select $1", 200)
if err != nil {
panic(err)
}
// works with sqlx's named queries.
_, err = dbx.NamedQueryContext(ctx, "select :value", map[string]any{"value": 300})
if err != nil {
panic(err)
}
// Create a logger using slog.
jsonlog := slog.New(slog.NewJSONHandler(os.Stdout, nil))
slogDriver, err := qslog.Register("postgres", jsonlog)
if err != nil {
panic(err)
}
slogDb, err := sql.Open(slogDriver, connStr)
if err != nil {
panic(err)
}
rows, err = slogDb.Query("select $1", 300)
if err != nil {
panic(err)
}
defer rows.Close()
// Create a logger that only logs slow queries.
slowDriver, err := querypulse.Register(
"postgres",
querypulse.Options{
OnSuccess: func(ctx context.Context, query string, args []any, duration time.Duration) {
if duration > 10*time.Second {
slog.Info("slow query", "query", query, "args", args, "took_ms", duration)
}
},
})
if err != nil {
panic(err)
}
slowDb, err := sql.Open(slowDriver, connStr)
if err != nil {
panic(err)
}
rows, err = slowDb.Query("select $1", 400)
if err != nil {
panic(err)
}
defer rows.Close()
}