forked from gobuffalo/pop
-
Notifications
You must be signed in to change notification settings - Fork 0
/
columns_for_struct.go
57 lines (49 loc) · 1.1 KB
/
columns_for_struct.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
package columns
import (
"reflect"
)
// ColumnsForStruct returns a Columns instance for
// the struct passed in.
func ColumnsForStruct(s interface{}, tableName string) (columns Columns) {
return ColumnsForStructWithAlias(s, tableName, "")
}
func ColumnsForStructWithAlias(s interface{}, tableName string, tableAlias string) (columns Columns) {
columns = NewColumnsWithAlias(tableName, tableAlias)
defer func() {
if r := recover(); r != nil {
columns = NewColumnsWithAlias(tableName, tableAlias)
columns.Add("*")
}
}()
st := reflect.TypeOf(s)
if st.Kind() == reflect.Ptr {
st = st.Elem()
}
if st.Kind() == reflect.Slice {
st = st.Elem()
if st.Kind() == reflect.Ptr {
st = st.Elem()
}
}
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
}