forked from go-gorm/gorm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfield.go
129 lines (112 loc) · 2.63 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
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
package gorm
import (
"database/sql"
"reflect"
"strconv"
"strings"
"time"
)
type Field struct {
Name string
Value interface{}
model *Model
dbName string
isPrimaryKey bool
autoCreateTime bool
autoUpdateTime bool
foreignKey string
beforeAssociation bool
afterAssociation bool
reflectValue reflect.Value
structField reflect.StructField
}
func (f *Field) isBlank() bool {
return isBlank(f.reflectValue)
}
func (f *Field) isScanner() bool {
_, is_scanner := reflect.New(f.reflectValue.Type()).Interface().(sql.Scanner)
return is_scanner
}
func (f *Field) isTime() bool {
_, is_time := f.Value.(time.Time)
return is_time
}
func (f *Field) sqlTag() (str string) {
value := f.Value
if f.isScanner() {
value = f.reflectValue.Field(0).Interface()
}
reflect_value := f.reflectValue
switch reflect_value.Kind() {
case reflect.Slice:
return
case reflect.Struct:
if !f.isTime() && !f.isScanner() {
return
}
}
typ, addational_typ, size := parseSqlTag(f.structField.Tag.Get(f.model.do.db.tagIdentifier))
if typ == "-" {
return
}
if len(typ) == 0 {
if f.isPrimaryKey {
typ = f.model.do.dialect().PrimaryKeyTag(value, size)
} else {
typ = f.model.do.dialect().SqlTag(value, size)
}
}
if len(addational_typ) > 0 {
typ = typ + " " + addational_typ
}
return typ
}
func (f *Field) parseAssociation() {
reflect_value := f.reflectValue
switch reflect_value.Kind() {
case reflect.Slice:
foreign_key := f.model.typeName() + "Id"
if reflect.New(reflect_value.Type().Elem()).Elem().FieldByName(foreign_key).IsValid() {
f.foreignKey = foreign_key
}
f.afterAssociation = true
case reflect.Struct:
if !f.isTime() && !f.isScanner() {
if f.model.reflectData().FieldByName(f.Name + "Id").IsValid() {
f.foreignKey = f.Name + "Id"
f.beforeAssociation = true
} else {
foreign_key := f.model.typeName() + "Id"
if reflect.New(reflect_value.Type()).Elem().FieldByName(foreign_key).IsValid() {
f.foreignKey = foreign_key
}
f.afterAssociation = true
}
}
}
}
func parseSqlTag(str string) (typ string, addational_typ string, size int) {
if str == "-" {
typ = str
} else if str != "" {
tags := strings.Split(str, ";")
m := make(map[string]string)
for _, value := range tags {
v := strings.Split(value, ":")
k := strings.Trim(strings.ToUpper(v[0]), " ")
if len(v) == 2 {
m[k] = v[1]
} else {
m[k] = k
}
}
if len(m["SIZE"]) > 0 {
size, _ = strconv.Atoi(m["SIZE"])
}
if len(m["TYPE"]) > 0 {
typ = m["TYPE"]
}
addational_typ = m["NOT NULL"] + " " + m["UNIQUE"]
}
return
}