-
Notifications
You must be signed in to change notification settings - Fork 35
/
xun.go
610 lines (537 loc) · 13 KB
/
xun.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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
package xun
import (
"database/sql/driver"
"encoding/json"
"fmt"
"math"
"reflect"
"regexp"
"strconv"
"strings"
"time"
"github.com/yaoapp/xun/utils"
)
var matchFirstCap = regexp.MustCompile("(.)([A-Z][a-z]+)")
var matchAllCap = regexp.MustCompile("([a-z0-9])([A-Z])")
// ToSnakeCase convert camel case string to snake case
func ToSnakeCase(str string) string {
snake := matchFirstCap.ReplaceAllString(str, "${1}_${2}")
snake = matchAllCap.ReplaceAllString(snake, "${1}_${2}")
return strings.ToLower(snake)
}
// UpperFirst upcase the first letter
func UpperFirst(str string) string {
if len(str) < 1 {
return strings.ToUpper(str)
}
first := strings.ToUpper(string(str[0]))
other := str[1:]
return first + other
}
// MakeTime Create a new time struct
func MakeTime(value ...interface{}) T {
if len(value) == 0 {
return T{Time: time.Now()}
}
return T{
Time: value[0],
}
}
// ToTime cast the T to time.Time
func (t T) ToTime(formats ...string) (time.Time, error) {
if len(formats) == 0 {
formats = []string{
"2006-01-02T15:04:05-0700",
"2006-01-02T15:04:05.000Z",
"2006-01-02T15:04:05",
"2006-01-02 15:04:05",
"2006-01-02",
"15:04:05",
}
}
switch t.Time.(type) {
case int, int64, int32, int16, int8, uint8:
var err error
var i int64
var s int64
strValue := fmt.Sprintf("%v", t.Time)
if len(strValue) == 10 {
i, err = strconv.ParseInt(strValue, 10, 64)
s = 0
if err != nil {
return time.Now(), err
}
} else if len(strValue) == 13 {
i, err = strconv.ParseInt(strValue[0:10], 10, 64)
if err != nil {
return time.Now(), err
}
s, err = strconv.ParseInt(strValue[10:13], 10, 64)
if err != nil {
return time.Now(), err
}
}
return time.Unix(i, s), nil
case string, []byte:
var err error
strValue := fmt.Sprintf("%s", t.Time)
dateValue := time.Now()
for _, format := range formats {
dateValue, err = time.Parse(format, strValue)
if err == nil {
return dateValue, nil
}
}
if err != nil {
return dateValue, fmt.Errorf("%s(%s)", err, formats)
}
return dateValue, fmt.Errorf("cannot parse %s (%s)", t.Time, formats)
case time.Time:
return t.Time.(time.Time), nil
default:
return time.Now(), nil
}
}
// MustToTime cast the T to time.Time
func (t T) MustToTime(formats ...string) time.Time {
value, err := t.ToTime(formats...)
if err != nil {
panic(err)
}
return value
}
// IsNull determine if the time is null
func (t T) IsNull() bool {
return utils.IsNil(t.Time)
}
// Scan for db scan
func (t *T) Scan(src interface{}) error {
*t = MakeTime(src)
return nil
}
// Value for db driver value
func (t *T) Value() (driver.Value, error) {
return t.ToTime()
}
// MarshalJSON for json marshalJSON
func (t *T) MarshalJSON() ([]byte, error) {
return json.Marshal(t.Time)
}
// UnmarshalJSON for json marshalJSON
func (t *T) UnmarshalJSON(data []byte) error {
*t = MakeTime(data)
return nil
}
// MakeRow create a new R struct alias MakeR
func MakeRow(value ...interface{}) R {
return MakeR(value...)
}
// MakeR create a new R struct
func MakeR(value ...interface{}) R {
if len(value) == 0 {
return R{}
}
v := value[0]
reflectValue := reflect.ValueOf(v)
reflectValue = reflect.Indirect(reflectValue)
switch reflectValue.Kind() {
case reflect.Slice, reflect.Array:
if reflectValue.Len() > 0 {
return MakeR(reflectValue.Index(0).Interface())
}
return MakeR()
case reflect.Map:
return mapToR(v)
case reflect.Struct:
return structToR(v)
}
panic(fmt.Errorf("The type of given value is %s, should be struct", reflectValue.Type().String()))
}
// MakePaginator create a new P struct alias MakeP
func MakePaginator(total int, pageSize int, currentPage int, items ...interface{}) P {
return MakeP(total, pageSize, currentPage, items...)
}
// MakeP create a new P struct
func MakeP(total int, pageSize int, currentPage int, items ...interface{}) P {
if pageSize < 1 {
pageSize = 15
}
if currentPage < 1 {
currentPage = 1
}
pagecnt := int(math.Ceil(float64(total) / float64(pageSize)))
next := currentPage + 1
prev := currentPage - 1
last := pagecnt
if next > pagecnt {
next = -1
}
if prev <= 0 {
prev = -1
}
return P{
Items: items,
Total: total,
TotalPages: pagecnt,
PageSize: pageSize,
CurrentPage: currentPage,
NextPage: next,
PreviousPage: prev,
LastPage: last,
}
}
// Value get the value of the given key ( alias Get)
func (row R) Value(key interface{}) interface{} {
return row.Get(key)
}
// Get get the value of the given key
func (row R) Get(key interface{}) interface{} {
keys := strings.Split(fmt.Sprintf("%v", key), ".")
nextRow := row
length := len(keys) - 1
for i, k := range keys {
value, has := nextRow[k]
if !has {
return nil
}
if length == i {
return value
}
nextRow = MakeR(value)
}
return nil
}
// GetTime get the value of the given key, and cast the type to xun.T
func (row R) GetTime(key interface{}) T {
value := row.Get(key)
return MakeTime(value)
}
// GetString get the string value of the given key
func (row R) GetString(key interface{}) string {
value := row.Get(key)
if value == nil {
return ""
}
if stringVal, ok := value.(string); ok {
return stringVal
}
return fmt.Sprintf("%v", value)
}
// GetInt get the int value of the given key
func (row R) GetInt(key interface{}) int {
value := row.Get(key)
num := MakeN(value)
return num.MustInt()
}
// GetBool get the int value of the given key
func (row R) GetBool(key interface{}) bool {
value := row.Get(key)
switch value.(type) {
case bool:
return value.(bool)
case int, int64, int32, int16, int8, uint64, uint32, uint16, uint8, float32, float64:
value := MakeN(value).MustInt()
return value > 0
case string:
return value.(string) != ""
}
return false
}
// GetFloat get the float value of the given key
func (row R) GetFloat(key interface{}, places int) float64 {
value := row.Get(key)
num := MakeN(value)
return num.MustToFixed(places)
}
// MustGet get the value of the given key, if key does not exits painc
func (row R) MustGet(key interface{}) interface{} {
keys := strings.Split(fmt.Sprintf("%v", key), ".")
nextRow := row
length := len(keys) - 1
for i, k := range keys {
value, has := nextRow[k]
if !has {
panic(fmt.Errorf("the key %v does not exists", key))
}
if length == i {
return value
}
nextRow = MakeR(value)
}
return nil
}
// Has detemind if has the given key
func (row R) Has(key string) bool {
keys := strings.Split(fmt.Sprintf("%v", key), ".")
nextRow := row
length := len(keys) - 1
for i, k := range keys {
value, has := nextRow[k]
if !has {
return false
}
if length == i {
return true
}
nextRow = MakeR(value)
}
return true
}
// Del delete value with given key
func (row R) Del(key string) {
delete(row, key)
}
// ToMap cast to map[string]interface{}
func (row R) ToMap() map[string]interface{} {
res := map[string]interface{}{}
for k, v := range row {
res[k] = v
}
return res
}
// Keys get keys of R
func (row R) Keys() []interface{} {
keys := []interface{}{}
for k := range row {
keys = append(keys, k)
}
return keys
}
// KeysString get keys of R
func (row R) KeysString() []string {
keys := []string{}
for k := range row {
keys = append(keys, k)
}
return keys
}
// IsEmpty determine if the row is null
func (row R) IsEmpty() bool {
return len(row.Keys()) == 0
}
// Merge get keys of R
func (row *R) Merge(v ...interface{}) {
values := MakeRSlice(v...)
for _, value := range values {
for k, v := range value {
(*row)[k] = v
}
}
}
// MakeRows convert any struct to R slice alias MakeRSlice
func MakeRows(value ...interface{}) []R {
return MakeRSlice(value...)
}
// MakeRSlice convert any struct to R slice
func MakeRSlice(value ...interface{}) []R {
if len(value) == 0 {
return []R{}
}
values := []interface{}{}
if len(value) == 1 {
reflectValue := reflect.ValueOf(value[0])
reflectValue = reflect.Indirect(reflectValue)
reflectKind := reflectValue.Kind()
if reflectKind == reflect.Slice || reflectKind == reflect.Array {
for i := 0; i < reflectValue.Len(); i++ {
values = append(values, reflectValue.Index(i).Interface())
}
} else {
values = append(values, value[0])
}
} else {
values = value
}
res := []R{}
for _, v := range values {
res = append(res, MakeR(v))
}
return res
}
func mapToR(value interface{}) R {
r := R{}
reflectValue := reflect.ValueOf(value)
reflectValue = reflect.Indirect(reflectValue)
if reflectValue.Kind() == reflect.Map {
for _, key := range reflectValue.MapKeys() {
k := fmt.Sprintf("%v", key)
v := reflectValue.MapIndex(key).Interface()
r[k] = v
}
}
return r
}
func structToR(value interface{}) R {
r := R{}
reflectValue := reflect.ValueOf(value)
reflectValue = reflect.Indirect(reflectValue)
reflectType := reflectValue.Type()
if reflectValue.Kind() == reflect.Struct {
for i := 0; i < reflectValue.NumField(); i++ {
if !reflectValue.Field(i).CanInterface() {
continue
}
tag := GetTagName(reflectType.Field(i), "json")
field := reflectValue.Field(i).Interface()
if tag != "" && tag != "-" {
kind := reflectType.Field(i).Type.Kind()
if kind == reflect.Struct {
r[tag] = structToR(field)
} else if kind == reflect.Slice || kind == reflect.Array {
r[tag] = MakeRSlice(field)
} else {
r[tag] = field
}
}
}
}
return r
}
// GetTagName get the tag name of the reflect.StructField
func GetTagName(field reflect.StructField, name string) string {
tag := field.Tag.Get(name)
if tag == "" {
tag = ToSnakeCase(field.Name)
}
return tag
}
// MakeNum Create a new xun.N struct ( alias MakeN )
func MakeNum(v interface{}) N {
return MakeN(v)
}
// MakeN Create a new xun.N struct
func MakeN(v interface{}) N {
if num, ok := v.(N); ok {
return num
}
return N{Number: v}
}
// Scan for db scan
func (n *N) Scan(src interface{}) error {
*n = MakeN(src)
return nil
}
// Value for db driver value
func (n *N) Value() (driver.Value, error) {
return n.Number, nil
}
// MarshalJSON for json marshalJSON
func (n *N) MarshalJSON() ([]byte, error) {
return json.Marshal(n.Number)
}
// UnmarshalJSON for json marshalJSON
func (n *N) UnmarshalJSON(data []byte) error {
var v float64
err := json.Unmarshal(data, &v)
if err != nil {
return err
}
*n = MakeN(v)
return nil
}
// ToFixed the return value is the type of float64 and keeps the given decimal places
func (n N) ToFixed(places int) (float64, error) {
num, err := n.Float64()
if err != nil {
return 0, err
}
output := math.Pow(10, float64(places))
num = num * output
return float64(int(num+math.Copysign(0.5, num))) / output, nil
}
// MustToFixed the return value is the type of float64 and keeps the given decimal places
func (n N) MustToFixed(places int) float64 {
value, err := n.ToFixed(places)
utils.PanicIF(err)
return value
}
// Float64 the return value is the type of float64
func (n N) Float64() (float64, error) {
if n.Number == nil {
return 0, fmt.Errorf("the value is nil")
}
value, ok := n.Number.(string)
if !ok {
value = fmt.Sprintf("%v", n.Number)
}
num, err := strconv.ParseFloat(value, 64)
if err != nil {
return 0, err
}
return num, nil
}
// MustFloat64 the return value is the type of float64
func (n N) MustFloat64() float64 {
value, err := n.Float64()
utils.PanicIF(err)
return value
}
// Int64 the return value is the type of int64 and remove the decimal
func (n N) Int64() (int64, error) {
if n.Number == nil {
return 0, fmt.Errorf("the value is nil")
}
return strconv.ParseInt(fmt.Sprintf("%v", n.Number), 10, 64)
}
// MustInt64 the return value is the type of int64 and remove the decimal
func (n N) MustInt64() int64 {
value, err := n.Int64()
utils.PanicIF(err)
return value
}
// Int32 the return value is the type of int64 and remove the decimal
func (n N) Int32() (int32, error) {
if n.Number == nil {
return 0, fmt.Errorf("the value is nil")
}
value, err := strconv.ParseInt(fmt.Sprintf("%v", n.Number), 10, 32)
if err != nil {
return 0, err
}
return int32(value), nil
}
// MustInt32 the return value is the type of int64 and remove the decimal
func (n N) MustInt32() int32 {
value, err := n.Int32()
utils.PanicIF(err)
return value
}
// Int the return value is the type of int and remove the decimal
func (n N) Int() (int, error) {
if n.Number == nil {
return 0, fmt.Errorf("the value is nil")
}
if value, ok := n.Number.(bool); ok {
if value {
return 1, nil
}
return 0, nil
}
value, err := strconv.ParseInt(fmt.Sprintf("%v", n.Number), 10, 64)
if err != nil {
return 0, err
}
return int(value), nil
}
// MustInt the return value is the type of int and remove the decimal
func (n N) MustInt() int {
value, err := n.Int()
utils.PanicIF(err)
return value
}
// CastType cast type
func CastType(value *reflect.Value, from reflect.Kind, to reflect.Kind) bool {
if from == to {
return true
}
typ := fmt.Sprintf("%s->%s", from.String(), to.String())
switch typ {
case "int64->int":
*value = reflect.ValueOf(int(value.Interface().(int64)))
return true
case "float32->float64":
*value = reflect.ValueOf(float64(value.Interface().(float32)))
return true
}
return false
}