forked from uptrace/bun
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
84 lines (66 loc) · 1.94 KB
/
client.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
package main
import (
"context"
"database/sql"
"fmt"
"time"
"github.com/brianvoe/gofakeit/v5"
"github.com/uptrace/bun"
"github.com/uptrace/bun/dialect/pgdialect"
"github.com/uptrace/bun/driver/pgdriver"
"github.com/uptrace/bun/extra/bunotel"
"github.com/uptrace/uptrace-go/uptrace"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/codes"
)
var tracer = otel.Tracer("github.com/uptrace/bun/example/opentelemetry")
func main() {
ctx := context.Background()
uptrace.ConfigureOpentelemetry(
// copy your project DSN here or use UPTRACE_DSN env var
// uptrace.WithDSN("http://project2_secret_token@localhost:14317/2"),
uptrace.WithServiceName("myservice"),
uptrace.WithServiceVersion("v1.0.0"),
)
defer uptrace.Shutdown(ctx)
dsn := "postgres://uptrace:uptrace@localhost:5432/uptrace?sslmode=disable"
sqldb := sql.OpenDB(pgdriver.NewConnector(pgdriver.WithDSN(dsn)))
db := bun.NewDB(sqldb, pgdialect.New())
db.AddQueryHook(bunotel.NewQueryHook(
bunotel.WithDBName("uptrace"),
bunotel.WithFormattedQueries(true),
))
// db.AddQueryHook(bundebug.NewQueryHook(bundebug.WithVerbose(true)))
if err := db.ResetModel(ctx, (*TestModel)(nil)); err != nil {
panic(err)
}
for i := 0; i < 1e6; i++ {
ctx, rootSpan := tracer.Start(ctx, "handleRequest")
if err := handleRequest(ctx, db); err != nil {
rootSpan.RecordError(err)
rootSpan.SetStatus(codes.Error, err.Error())
}
rootSpan.End()
if i == 0 {
fmt.Printf("view trace: %s\n", uptrace.TraceURL(rootSpan))
}
time.Sleep(time.Second)
}
}
type TestModel struct {
ID int64 `bun:",pk,autoincrement"`
Name string
}
func handleRequest(ctx context.Context, db *bun.DB) error {
model := &TestModel{
Name: gofakeit.Name(),
}
if _, err := db.NewInsert().Model(model).Exec(ctx); err != nil {
return err
}
// Check that data can be selected without any errors.
if err := db.NewSelect().Model(model).WherePK().Scan(ctx); err != nil {
return err
}
return nil
}