-
-
Notifications
You must be signed in to change notification settings - Fork 397
/
model_table.go
107 lines (89 loc) · 2.09 KB
/
model_table.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package orm
import (
"errors"
"fmt"
"reflect"
)
type tableModel interface {
Model
Table() *Table
Relation() *Relation
AppendParam([]byte, string) ([]byte, bool)
Join(string, func(*Query) (*Query, error)) (bool, *join)
GetJoin(string) *join
GetJoins() []join
AddJoin(join) *join
Root() reflect.Value
Index() []int
ParentIndex() []int
Mount(reflect.Value)
Value() reflect.Value
scanColumn(int, string, []byte) (bool, error)
}
func newTableModel(value interface{}) (tableModel, error) {
if value, ok := value.(tableModel); ok {
return value, nil
}
v := reflect.ValueOf(value)
if !v.IsValid() {
return nil, errors.New("pg: Model(nil)")
}
if v.Kind() != reflect.Ptr {
return nil, fmt.Errorf("pg: Model(non-pointer %T)", value)
}
if v.IsNil() {
typ := v.Type().Elem()
if typ.Kind() == reflect.Struct {
return newStructTableModelType(typ), nil
}
return nil, errors.New("pg: Model(nil)")
}
return newTableModelValue(v.Elem())
}
func newTableModelValue(v reflect.Value) (tableModel, error) {
switch v.Kind() {
case reflect.Struct:
return newStructTableModelValue(v), nil
case reflect.Slice:
structType := sliceElemType(v)
if structType.Kind() == reflect.Struct {
m := sliceTableModel{
structTableModel: structTableModel{
table: Tables.Get(structType),
root: v,
},
slice: v,
}
m.init(v.Type())
return &m, nil
}
}
return nil, fmt.Errorf("pg: Model(unsupported %s)", v.Type())
}
func newTableModelIndex(root reflect.Value, index []int, rel *Relation) (tableModel, error) {
typ := typeByIndex(root.Type(), index)
if typ.Kind() == reflect.Struct {
return &structTableModel{
table: Tables.Get(typ),
rel: rel,
root: root,
index: index,
}, nil
}
if typ.Kind() == reflect.Slice {
structType := indirectType(typ.Elem())
if structType.Kind() == reflect.Struct {
m := sliceTableModel{
structTableModel: structTableModel{
table: Tables.Get(structType),
rel: rel,
root: root,
index: index,
},
}
m.init(typ)
return &m, nil
}
}
return nil, fmt.Errorf("pg: NewModel(%s)", typ)
}