model_table.go
2.0 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
96
97
98
99
100
101
102
103
package orm
import (
"fmt"
"reflect"
"github.com/go-pg/pg/types"
)
type TableModel interface {
Model
IsNil() bool
Table() *Table
Relation() *Relation
AppendParam([]byte, QueryFormatter, string) ([]byte, bool)
Join(string, func(*Query) (*Query, error)) *join
GetJoin(string) *join
GetJoins() []join
AddJoin(join) *join
Root() reflect.Value
Index() []int
ParentIndex() []int
Mount(reflect.Value)
Kind() reflect.Kind
Value() reflect.Value
setSoftDeleteField()
scanColumn(int, string, types.Reader, int) (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, errModelNil
}
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 newStructTableModel(GetTable(typ)), nil
}
return nil, errModelNil
}
return newTableModelValue(v.Elem())
}
func newTableModelValue(v reflect.Value) (TableModel, error) {
switch v.Kind() {
case reflect.Struct:
return newStructTableModelValue(v), nil
case reflect.Slice:
elemType := sliceElemType(v)
if elemType.Kind() == reflect.Struct {
return newSliceTableModel(v, elemType), 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: GetTable(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: GetTable(structType),
rel: rel,
root: root,
index: index,
},
}
m.init(typ)
return &m, nil
}
}
return nil, fmt.Errorf("pg: NewModel(%s)", typ)
}