-
-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
struct_row.go
93 lines (74 loc) · 2.01 KB
/
struct_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
90
91
92
93
package sqlx
import (
"fmt"
"reflect"
"strings"
"github.com/kataras/iris/v12/x/reflex"
)
// DefaultTag is the default struct field tag.
var DefaultTag = "db"
// ColumnNameFunc is the function which converts a struct field name to a database column name.
type ColumnNameFunc = func(string) string
func convertStructToColumns(typ reflect.Type, nameFunc ColumnNameFunc) (map[string]*Column, error) {
if kind := typ.Kind(); kind != reflect.Struct {
return nil, fmt.Errorf("convert struct: invalid type: expected a struct value but got: %q", kind.String())
}
// Retrieve only fields valid for database.
fields := reflex.LookupFields(typ, "")
columns := make(map[string]*Column, len(fields))
for i, field := range fields {
column, ok, err := convertStructFieldToColumn(field, DefaultTag, nameFunc)
if !ok {
continue
}
if err != nil {
return nil, fmt.Errorf("convert struct: field name: %q: %w", field.Name, err)
}
column.Index = i
columns[column.Name] = column
}
return columns, nil
}
func convertStructFieldToColumn(field reflect.StructField, optionalTag string, nameFunc ColumnNameFunc) (*Column, bool, error) {
c := &Column{
Name: nameFunc(field.Name),
FieldIndex: field.Index,
}
fieldTag, ok := field.Tag.Lookup(optionalTag)
if ok {
if fieldTag == "-" {
return nil, false, nil
}
if err := parseOptions(fieldTag, c); err != nil {
return nil, false, err
}
}
return c, true, nil
}
func parseOptions(fieldTag string, c *Column) error {
options := strings.Split(fieldTag, ",")
for _, opt := range options {
if opt == "" {
continue // skip empty.
}
var key, value string
kv := strings.Split(opt, "=") // When more options come to play.
switch len(kv) {
case 2:
key = kv[0]
value = kv[1]
case 1:
c.Name = kv[0]
return nil
default:
return fmt.Errorf("option: %s: expected key value separated by '='", opt)
}
switch key {
case "name":
c.Name = value
default:
return fmt.Errorf("unexpected tag option: %s", key)
}
}
return nil
}