-
Notifications
You must be signed in to change notification settings - Fork 5
/
field.go
67 lines (63 loc) · 1.57 KB
/
field.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
package orm
import (
"database/sql/driver"
"github.com/iancoleman/strcase"
"reflect"
"strings"
)
type field struct {
Name string
IsPK bool
Virtual bool
IsCreatedAt bool
IsUpdatedAt bool
IsDeletedAt bool
Nullable bool
Default any
Type reflect.Type
}
func getFieldConfiguratorFor(fieldConfigurators []*FieldConfigurator, name string) *FieldConfigurator {
for _, fc := range fieldConfigurators {
if fc.fieldName == name {
return fc
}
}
return &FieldConfigurator{}
}
func fieldMetadata(ft reflect.StructField, fieldConfigurators []*FieldConfigurator) []*field {
var fms []*field
fc := getFieldConfiguratorFor(fieldConfigurators, ft.Name)
baseFm := &field{}
baseFm.Type = ft.Type
fms = append(fms, baseFm)
if fc.column != "" {
baseFm.Name = fc.column
} else {
baseFm.Name = strcase.ToSnake(ft.Name)
}
if strings.ToLower(ft.Name) == "id" || fc.primaryKey {
baseFm.IsPK = true
}
if strings.ToLower(ft.Name) == "createdat" || fc.isCreatedAt {
baseFm.IsCreatedAt = true
}
if strings.ToLower(ft.Name) == "updatedat" || fc.isUpdatedAt {
baseFm.IsUpdatedAt = true
}
if strings.ToLower(ft.Name) == "deletedat" || fc.isDeletedAt {
baseFm.IsDeletedAt = true
}
if ft.Type.Kind() == reflect.Struct || ft.Type.Kind() == reflect.Ptr {
t := ft.Type
if ft.Type.Kind() == reflect.Ptr {
t = ft.Type.Elem()
}
if !t.Implements(reflect.TypeOf((*driver.Valuer)(nil)).Elem()) {
for i := 0; i < t.NumField(); i++ {
fms = append(fms, fieldMetadata(t.Field(i), fieldConfigurators)...)
}
fms = fms[1:]
}
}
return fms
}