-
Notifications
You must be signed in to change notification settings - Fork 17
/
row.go
89 lines (70 loc) · 1.71 KB
/
row.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
package crud
type RowValue struct {
SQLColumn string
Value interface{}
}
type Row struct {
SQLTableName string
Values []*RowValue
}
func (row *Row) SQLValues() map[string]interface{} {
result := map[string]interface{}{}
for _, v := range row.Values {
result[v.SQLColumn] = v.Value
}
return result
}
// Takes a valid struct record and returns a crud.Row instance.
func newRow(st interface{}) (*Row, error) {
values, err := GetRowValuesOf(st)
if err != nil {
return nil, err
}
tableName := SQLTableNameOf(st)
if customTableName, ok := lookupCustomTableName(st); ok {
tableName = customTableName
}
return &Row{
SQLTableName: tableName,
Values: values,
}, nil
}
// Scans given struct record and returns a list of crud.Row instances for each
// struct field. It's useful for extracting values and corresponding SQL meta information
// from structs representing database tables.
func GetRowValuesOf(st interface{}) ([]*RowValue, error) {
fields, err := collectRows(st, []*RowValue{})
if err != nil {
return nil, err
}
return fields, nil
}
func collectRows(st interface{}, rows []*RowValue) ([]*RowValue, error) {
iter := NewFieldIteration(st)
for iter.Next() {
if iter.IsEmbeddedStruct() {
if _rows, err := collectRows(iter.ValueField().Interface(), rows); err != nil {
return nil, err
} else {
rows = _rows
}
continue
}
sqlOptions, err := iter.SQLOptions()
if err != nil {
return nil, err
}
if sqlOptions.Ignore {
continue
}
value := iter.Value()
if n, ok := value.(int); ok && sqlOptions.AutoIncrement > 0 && n == 0 {
continue
}
rows = append(rows, &RowValue{
SQLColumn: sqlOptions.Name,
Value: value,
})
}
return rows, nil
}