-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathrow.go
More file actions
95 lines (74 loc) · 1.89 KB
/
row.go
File metadata and controls
95 lines (74 loc) · 1.89 KB
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
package crud
import "time"
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(driver string, st interface{}) (*Row, error) {
values, err := GetRowValuesOf(driver, st)
if err != nil {
return nil, err
}
tableName := SQLTableNameOf(driver, st)
if customTableName, ok := lookupCustomTableName(driver, 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(driver string, st interface{}) ([]*RowValue, error) {
fields, err := collectRows(driver, st, []*RowValue{})
if err != nil {
return nil, err
}
return fields, nil
}
func collectRows(driver string, st interface{}, rows []*RowValue) ([]*RowValue, error) {
iter := NewFieldIteration(driver, st)
for iter.Next() {
if iter.IsEmbeddedStruct() {
if _rows, err := collectRows(driver, 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
}
if t, ok := value.(time.Time); ok && t.IsZero() {
continue
}
rows = append(rows, &RowValue{
SQLColumn: sqlOptions.Name,
Value: value,
})
}
return rows, nil
}