forked from jlelse/GoBlog
-
Notifications
You must be signed in to change notification settings - Fork 0
/
databaseHooks.go
64 lines (58 loc) · 1.44 KB
/
databaseHooks.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
package main
import (
"context"
"database/sql"
"fmt"
"log"
"time"
"github.com/spf13/cast"
"go.goblog.app/app/pkgs/bufferpool"
)
const dbHooksBegin contextKey = "begin"
func (db *database) dbBefore(ctx context.Context, _ string, _ ...any) context.Context {
if !db.debug {
return ctx
}
return context.WithValue(ctx, dbHooksBegin, time.Now())
}
func (db *database) dbAfter(ctx context.Context, query string, args ...any) {
if !db.debug {
return
}
dur := time.Since(ctx.Value(dbHooksBegin).(time.Time))
logBuilder := bufferpool.Get()
logBuilder.WriteString("\nQuery: ")
logBuilder.WriteString(`"`)
logBuilder.WriteString(query)
logBuilder.WriteString(`"`)
if len(args) > 0 {
logBuilder.WriteString("\nArgs: ")
for i, arg := range args {
if i > 0 {
logBuilder.WriteString(", ")
}
if named, ok := arg.(sql.NamedArg); ok && named.Name != "" {
logBuilder.WriteString("(")
logBuilder.WriteString(named.Name)
logBuilder.WriteString(`) "`)
logBuilder.WriteString(argToString(named.Value))
logBuilder.WriteString(`"`)
} else {
logBuilder.WriteString(`"`)
logBuilder.WriteString(argToString(arg))
logBuilder.WriteString(`"`)
}
}
}
logBuilder.WriteString("\nDuration: ")
logBuilder.WriteString(dur.String())
log.Println(logBuilder.String())
bufferpool.Put(logBuilder)
}
func argToString(arg any) string {
val := cast.ToString(arg)
if val == "" {
val = fmt.Sprintf("%v", arg)
}
return val
}