-
Notifications
You must be signed in to change notification settings - Fork 17
/
fields.go
80 lines (66 loc) · 1.4 KB
/
fields.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
package crud
import (
"github.com/azer/crud/v2/sql"
)
type Field struct {
Name string
Value interface{}
SQL *sql.Options
}
// Get DB fields of any valid struct given
func GetFieldsOf(st interface{}) ([]*Field, error) {
fields, err := collectFields(st, []*Field{})
if err != nil {
return nil, err
}
return fields, nil
}
func collectFields(st interface{}, fields []*Field) ([]*Field, error) {
iter := NewFieldIteration(st)
for iter.Next() {
if iter.IsEmbeddedStruct() {
if _fields, err := collectFields(iter.ValueField().Interface(), fields); err != nil {
return nil, err
} else {
fields = _fields
}
continue
}
sqlOptions, err := iter.SQLOptions()
if err != nil {
return nil, err
}
if sqlOptions.Ignore {
continue
}
fields = append(fields, &Field{
Name: iter.Name(),
Value: iter.Value(),
SQL: sqlOptions,
})
}
return fields, nil
}
// If no PK is specified, then set `id` to be PK.
func SetDefaultPK(fields []*Field) {
if HasPK(fields) {
return
}
for i, f := range fields {
if !f.SQL.IsPrimaryKey && f.SQL.Name == "id" && f.SQL.Type == "int" {
fields[i].SQL.IsAutoIncrementing = true
fields[i].SQL.AutoIncrement = 1
fields[i].SQL.IsRequired = true
fields[i].SQL.IsPrimaryKey = true
return
}
}
}
func HasPK(fields []*Field) bool {
for _, f := range fields {
if f.SQL.IsPrimaryKey {
return true
}
}
return false
}