forked from gobuffalo/pop
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcolumns_for_struct.go
More file actions
52 lines (45 loc) · 1008 Bytes
/
columns_for_struct.go
File metadata and controls
52 lines (45 loc) · 1008 Bytes
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
package columns
import "reflect"
// ColumnsForStruct returns a Columns instance for
// the struct passed in.
func ColumnsForStruct(s interface{}, tableName string) (columns Columns) {
columns = NewColumns(tableName)
defer func() {
if r := recover(); r != nil {
columns = NewColumns(tableName)
columns.Add("*")
}
}()
st := reflect.TypeOf(s)
if st.Kind() == reflect.Ptr {
st = reflect.ValueOf(s).Elem().Type()
}
if st.Kind() == reflect.Slice {
v := reflect.ValueOf(s)
t := v.Type()
x := t.Elem().Elem()
n := reflect.New(x)
return ColumnsForStruct(n.Interface(), tableName)
}
field_count := st.NumField()
for i := 0; i < field_count; i++ {
field := st.Field(i)
tag := field.Tag.Get("db")
if tag == "" {
tag = field.Name
}
if tag != "-" {
rw := field.Tag.Get("rw")
if rw != "" {
tag = tag + "," + rw
}
cs := columns.Add(tag)
c := cs[0]
tag = field.Tag.Get("select")
if tag != "" {
c.SetSelectSQL(tag)
}
}
}
return columns
}