-
-
Notifications
You must be signed in to change notification settings - Fork 32
/
utl.go
205 lines (176 loc) · 4.55 KB
/
utl.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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
package nakama
import (
"bytes"
"encoding/base64"
"errors"
"fmt"
"io"
"mime"
"net/http"
"net/url"
"regexp"
"strings"
"sync"
"text/template"
"time"
"github.com/lib/pq"
)
const (
minPageSize = 1
defaultPageSize = 10
maxPageSize = 99
)
var queriesCache sync.Map
var (
reUUID = regexp.MustCompile("^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$")
reMultiSpace = regexp.MustCompile(`(\s)+`)
reMoreThan2Linebreaks = regexp.MustCompile(`(\n){2,}`)
reMentions = regexp.MustCompile(`\B@([a-zA-Z][a-zA-Z0-9_-]{0,17})(?:\b[^@]|$)`)
reTags = regexp.MustCompile(`\B#((?:\p{L}|\p{N}|_)+)(?:\b[^#]|$)`)
)
func isUniqueViolation(err error) bool {
pqerr, ok := err.(*pq.Error)
return ok && pqerr.Code == "23505"
}
func isForeignKeyViolation(err error) bool {
pqerr, ok := err.(*pq.Error)
return ok && pqerr.Code == "23503"
}
func buildQuery(text string, data map[string]interface{}) (string, []interface{}, error) {
var t *template.Template
v, ok := queriesCache.Load(text)
if !ok {
var err error
t, err = template.New("query").Parse(text)
if err != nil {
return "", nil, fmt.Errorf("could not parse sql query template: %w", err)
}
queriesCache.Store(text, t)
} else {
t = v.(*template.Template)
}
var wr bytes.Buffer
if err := t.Execute(&wr, data); err != nil {
return "", nil, fmt.Errorf("could not apply sql query data: %w", err)
}
query := wr.String()
args := []interface{}{}
for key, val := range data {
if !strings.Contains(query, "@"+key) {
continue
}
args = append(args, val)
query = strings.ReplaceAll(query, "@"+key, fmt.Sprintf("$%d", len(args)))
}
return query, args, nil
}
func normalizePageSize(i uint64) uint64 {
if i == 0 {
return defaultPageSize
}
if i < minPageSize {
return minPageSize
}
if i > maxPageSize {
return maxPageSize
}
return i
}
func smartTrim(s string) string {
oldLines := strings.Split(s, "\n")
newLines := []string{}
for _, line := range oldLines {
line = strings.TrimSpace(reMultiSpace.ReplaceAllString(line, "$1"))
newLines = append(newLines, line)
}
s = strings.Join(newLines, "\n")
s = reMoreThan2Linebreaks.ReplaceAllString(s, "$1$1")
return strings.TrimSpace(s)
}
func collectMentions(s string) []string {
m := map[string]struct{}{}
var u []string
for _, submatch := range reMentions.FindAllStringSubmatch(s, -1) {
val := submatch[1]
if _, ok := m[val]; !ok {
m[val] = struct{}{}
u = append(u, val)
}
}
return u
}
func collectTags(s string) []string {
m := map[string]struct{}{}
var u []string
for _, submatch := range reTags.FindAllStringSubmatch(s, -1) {
val := submatch[1]
if _, ok := m[val]; !ok {
m[val] = struct{}{}
u = append(u, val)
}
}
return u
}
func cloneURL(u *url.URL) *url.URL {
if u == nil {
return nil
}
u2 := new(url.URL)
*u2 = *u
if u.User != nil {
u2.User = new(url.Userinfo)
*u2.User = *u.User
}
return u2
}
func encodeCursor(key string, ts time.Time) string {
s := fmt.Sprintf("%s,%s", key, ts.Format(time.RFC3339Nano))
return base64.StdEncoding.EncodeToString([]byte(s))
}
func encodeSimpleCursor(key string) string {
return base64.StdEncoding.EncodeToString([]byte(key))
}
func decodeCursor(s string) (string, time.Time, error) {
b, err := base64.StdEncoding.DecodeString(s)
if err != nil {
return "", time.Time{}, fmt.Errorf("could not base64 decode cursor: %w", err)
}
parts := strings.Split(string(b), ",")
if len(parts) != 2 {
return "", time.Time{}, errors.New("expected cursor to have two items split by comma")
}
ts, err := time.Parse(time.RFC3339Nano, parts[1])
if err != nil {
return "", time.Time{}, fmt.Errorf("could not parse cursor timestamp: %w", err)
}
key := parts[0]
return key, ts, nil
}
func decodeSimpleCursor(s string) (string, error) {
b, err := base64.StdEncoding.DecodeString(s)
if err != nil {
return "", fmt.Errorf("could not base64 decode cursor: %w", err)
}
return string(b), nil
}
func detectContentType(r io.ReadSeeker) (string, error) {
// http.DetectContentType uses at most 512 bytes to make its decision.
h := make([]byte, 512)
_, err := r.Read(h)
if err != nil {
return "", fmt.Errorf("detect content type: read head: %w", err)
}
// Reset the reader so it can be used again.
_, err = r.Seek(0, io.SeekStart)
if err != nil {
return "", fmt.Errorf("detect content type: seek to start: %w", err)
}
mt, _, err := mime.ParseMediaType(http.DetectContentType(h))
if err != nil {
return "", fmt.Errorf("detect content type: %w", err)
}
return mt, nil
}
func ptrString(v string) *string {
return &v
}