-
Notifications
You must be signed in to change notification settings - Fork 0
/
comment.go
77 lines (67 loc) · 1.32 KB
/
comment.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
package sqlcommenter
import (
"bytes"
"context"
"strings"
"sync"
)
const (
commentStart = "/*"
commentEnd = "*/"
)
// Comment adds comments to query using provided options.
func Comment(ctx context.Context, query string, opts ...Option) string {
if len(opts) == 0 {
return query
}
if strings.Contains(query, commentStart) {
return query
}
return newCommenter(opts...).comment(ctx, query)
}
func newCommenter(opts ...Option) *commenter {
cmt := &commenter{}
for _, opt := range opts {
opt(cmt)
}
return cmt
}
type commenter struct {
providers []AttrProvider
}
func (c *commenter) comment(ctx context.Context, query string) string {
attrs := c.attrs(ctx)
if len(attrs) == 0 {
return query
}
buf := bufPool.Get().(*bytes.Buffer)
defer func() {
buf.Reset()
bufPool.Put(buf)
}()
buf.WriteString(query)
buf.WriteByte(' ')
buf.WriteString(commentStart)
attrs.encode(buf)
buf.WriteString(commentEnd)
return buf.String()
}
func (c *commenter) attrs(ctx context.Context) Attrs {
switch len(c.providers) {
case 0:
return nil
case 1:
return c.providers[0].GetAttrs(ctx)
default:
attrs := make(Attrs)
for _, prov := range c.providers {
attrs.Update(prov.GetAttrs(ctx))
}
return attrs
}
}
var bufPool = sync.Pool{
New: func() interface{} {
return bytes.NewBuffer(make([]byte, 0, 100))
},
}