-
Notifications
You must be signed in to change notification settings - Fork 0
/
fields.go
68 lines (56 loc) · 1.16 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
package crud
import (
"github.com/azer/crud/v2/sql"
)
type Field struct {
Name string
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() {
sqlOptions, err := iter.SQLOptions()
if err != nil {
return nil, err
}
if sqlOptions.Ignore {
continue
}
fields = append(fields, &Field{
Name: iter.Name(),
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
}