-
Notifications
You must be signed in to change notification settings - Fork 4
/
utils.go
310 lines (280 loc) · 7.31 KB
/
utils.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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
package korm
import (
"crypto/rand"
"encoding/hex"
"errors"
"fmt"
"io"
"net/http"
"net/mail"
"os"
"reflect"
"strings"
"testing"
"time"
"github.com/kamalshkeir/kmap"
"github.com/kamalshkeir/kstrct"
)
func GenerateUUID() string {
var uuid [16]byte
_, err := io.ReadFull(rand.Reader, uuid[:])
if err != nil {
return ""
}
uuid[6] = (uuid[6] & 0x0f) | 0x40 // Version 4
uuid[8] = (uuid[8] & 0x3f) | 0x80 // Variant is 10
var buf [36]byte
encodeHex(buf[:], uuid)
return string(buf[:])
}
func encodeHex(dst []byte, uuid [16]byte) {
hex.Encode(dst, uuid[:4])
dst[8] = '-'
hex.Encode(dst[9:13], uuid[4:6])
dst[13] = '-'
hex.Encode(dst[14:18], uuid[6:8])
dst[18] = '-'
hex.Encode(dst[19:23], uuid[8:10])
dst[23] = '-'
hex.Encode(dst[24:], uuid[10:])
}
func RunEvery(t time.Duration, fn func(cancelChan chan struct{})) {
//Usage : go RunEvery(2 * time.Second,func(){})
cancel := make(chan struct{})
fn(cancel)
c := time.NewTicker(t)
loop:
for {
select {
case <-c.C:
fn(cancel)
case <-cancel:
break loop
}
}
}
func SliceContains[T comparable](elems []T, vs ...T) bool {
for _, s := range elems {
for _, v := range vs {
if v == s {
return true
}
}
}
return false
}
func DifferenceBetweenSlices[T comparable](slice1 []T, slice2 []T) []T {
var diff []T
// Loop two times, first to find slice1 strings not in slice2,
// second loop to find slice2 strings not in slice1
for i := 0; i < 2; i++ {
for _, s1 := range slice1 {
found := false
for _, s2 := range slice2 {
if s1 == s2 {
found = true
break
}
}
// String not found. We add it to return slice
if !found {
diff = append(diff, s1)
}
}
// Swap the slices, only if it was the first loop
if i == 0 {
slice1, slice2 = slice2, slice1
}
}
return diff
}
func RemoveFromSlice[T comparable](slice *[]T, elemsToRemove ...T) {
for i, elem := range *slice {
for _, e := range elemsToRemove {
if e == elem {
*slice = append((*slice)[:i], (*slice)[i+1:]...)
}
}
}
}
// Benchmark benchmark a function
func Benchmark(f func(), name string, iterations int) {
// Start the timer
start := time.Now()
// Run the function multiple times
var allocs int64
for i := 0; i < iterations; i++ {
allocs += int64(testing.AllocsPerRun(1, f))
}
// Stop the timer and calculate the elapsed time
elapsed := time.Since(start)
// Calculate the number of operations per second
opsPerSec := float64(iterations) / elapsed.Seconds()
// Calculate the number of allocations per operation
allocsPerOp := float64(allocs) / float64(iterations)
// Print the results
fmt.Println("---------------------------")
fmt.Println("Function", name)
fmt.Printf("Operations per second: %f\n", opsPerSec)
fmt.Printf("Allocations per operation: %f\n", allocsPerOp)
fmt.Println("---------------------------")
}
// GetMemoryTable get a table from memory for specified or first connected db
func GetMemoryTable(tbName string, dbName ...string) (TableEntity, error) {
dName := databases[0].Name
if len(dbName) > 0 {
dName = dbName[0]
}
db, err := GetMemoryDatabase(dName)
if err != nil {
return TableEntity{}, err
}
for _, t := range db.Tables {
if t.Name == tbName {
return t, nil
}
}
return TableEntity{}, errors.New("nothing found")
}
// GetMemoryTable get a table from memory for specified or first connected db
func GetMemoryTableAndDB(tbName string, dbName ...string) (TableEntity, DatabaseEntity, error) {
dName := databases[0].Name
if len(dbName) > 0 {
dName = dbName[0]
}
db, err := GetMemoryDatabase(dName)
if err != nil {
return TableEntity{}, DatabaseEntity{}, err
}
for _, t := range db.Tables {
if t.Name == tbName {
return t, *db, nil
}
}
return TableEntity{}, DatabaseEntity{}, errors.New("nothing found")
}
// GetMemoryDatabases get all databases from memory
func GetMemoryDatabases() []DatabaseEntity {
return databases
}
// GetMemoryDatabase return the first connected database korm.DefaultDatabase if dbName "" or "default" else the matched db
func GetMemoryDatabase(dbName string) (*DatabaseEntity, error) {
if defaultDB == "" {
defaultDB = databases[0].Name
}
switch dbName {
case "", "default":
for i := range databases {
if databases[i].Name == defaultDB {
return &databases[i], nil
}
}
return nil, errors.New(dbName + "database not found")
default:
for i := range databases {
if databases[i].Name == dbName {
return &databases[i], nil
}
}
return nil, errors.New(dbName + "database not found")
}
}
func DownloadFile(filepath string, url string) error {
// Get the data
resp, err := http.Get(url)
if err != nil {
return err
}
defer resp.Body.Close()
// Create the file
out, err := os.Create(filepath)
if err != nil {
return err
}
defer out.Close()
// Write the body to file
_, err = io.Copy(out, resp.Body)
return err
}
// getStructInfos very useful to access all struct fields data using reflect package
func getStructInfos[T any](strctt *T, ignoreZeroValues ...bool) (fields []string, fValues map[string]any, fTypes map[string]string, fTags map[string][]string) {
fields = []string{}
fValues = map[string]any{}
fTypes = map[string]string{}
fTags = map[string][]string{}
s := reflect.ValueOf(strctt).Elem()
typeOfT := s.Type()
for i := 0; i < s.NumField(); i++ {
f := s.Field(i)
fname := typeOfT.Field(i).Name
fname = kstrct.ToSnakeCase(fname)
fvalue := f.Interface()
ftype := f.Type()
if len(ignoreZeroValues) > 0 && ignoreZeroValues[0] && strings.Contains(ftype.Name(), "Time") {
if v, ok := fvalue.(time.Time); ok {
if v.IsZero() {
continue
}
}
}
fields = append(fields, fname)
if f.Type().Kind() == reflect.Ptr {
fTypes[fname] = f.Type().Elem().String()
} else {
fTypes[fname] = f.Type().String()
}
fValues[fname] = fvalue
if ftag, ok := typeOfT.Field(i).Tag.Lookup("korm"); ok {
tags := strings.Split(ftag, ";")
fTags[fname] = tags
}
}
return fields, fValues, fTypes, fTags
}
// foreignkeyStat options are : "cascade","donothing", "noaction","setnull", "null","setdefault", "default"
func foreignkeyStat(fName, toTable, onDelete, onUpdate string) string {
toPk := "id"
if strings.Contains(toTable, ".") {
sp := strings.Split(toTable, ".")
if len(sp) == 2 {
toPk = sp[1]
}
}
fkey := "FOREIGN KEY (" + fName + ") REFERENCES " + toTable + "(" + toPk + ")"
switch onDelete {
case "cascade":
fkey += " ON DELETE CASCADE"
case "donothing", "noaction":
fkey += " ON DELETE NO ACTION"
case "setnull", "null":
fkey += " ON DELETE SET NULL"
case "setdefault", "default":
fkey += " ON DELETE SET DEFAULT"
}
switch onUpdate {
case "cascade":
fkey += " ON UPDATE CASCADE"
case "donothing", "noaction":
fkey += " ON UPDATE NO ACTION"
case "setnull", "null":
fkey += " ON UPDATE SET NULL"
case "setdefault", "default":
fkey += " ON UPDATE SET DEFAULT"
}
return fkey
}
func IsValidEmail(email string) bool {
_, err := mail.ParseAddress(email)
return err == nil
}
// SetCacheMaxMemory set max size of each cache cacheAllS AllM, minimum of 50 ...
func SetCacheMaxMemory(megaByte int) {
if megaByte < 100 {
megaByte = 100
}
cacheMaxMemoryMb = megaByte
cacheAllM = kmap.New[dbCache, []map[string]any](cacheMaxMemoryMb)
cacheAllS = kmap.New[dbCache, any](cacheMaxMemoryMb)
cacheQueryM = kmap.New[dbCache, any](cacheMaxMemoryMb)
cacheQueryS = kmap.New[dbCache, any](cacheMaxMemoryMb)
}