This repository has been archived by the owner on May 26, 2022. It is now read-only.
forked from gobuffalo/pop
/
has_many_association.go
170 lines (145 loc) · 4.13 KB
/
has_many_association.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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
package associations
import (
"fmt"
"reflect"
"github.com/gobuffalo/flect"
"github.com/gobuffalo/nulls"
"github.com/jmoiron/sqlx"
)
// hasManyAssociation is the implementation for the has_many
// association type in a model.
type hasManyAssociation struct {
tableName string
field reflect.StructField
value reflect.Value
ownerName string
ownerID interface{}
owner interface{}
fkID string
orderBy string
*associationSkipable
*associationComposite
}
func init() {
associationBuilders["has_many"] = hasManyAssociationBuilder
}
func hasManyAssociationBuilder(p associationParams) (Association, error) {
// Validates if ownerID is nil, this association will be skipped.
var skipped bool
ownerID := p.modelValue.FieldByName("ID")
if fieldIsNil(ownerID) {
skipped = true
}
return &hasManyAssociation{
owner: p.model,
tableName: p.popTags.Find("has_many").Value,
field: p.field,
value: p.modelValue.FieldByName(p.field.Name),
ownerName: p.modelType.Name(),
ownerID: ownerID.Interface(),
fkID: p.popTags.Find("fk_id").Value,
orderBy: p.popTags.Find("order_by").Value,
associationSkipable: &associationSkipable{
skipped: skipped,
},
associationComposite: &associationComposite{innerAssociations: p.innerAssociations},
}, nil
}
func (a *hasManyAssociation) Kind() reflect.Kind {
if a.field.Type.Kind() == reflect.Ptr {
return a.field.Type.Elem().Kind()
}
return a.field.Type.Kind()
}
func (a *hasManyAssociation) Interface() interface{} {
if a.value.Kind() == reflect.Ptr {
val := reflect.New(a.field.Type.Elem())
a.value.Set(val)
return a.value.Interface()
}
// This piece of code clears a slice in case it is filled with elements.
if a.value.Kind() == reflect.Slice || a.value.Kind() == reflect.Array {
valPointer := a.value.Addr()
valPointer.Elem().Set(reflect.MakeSlice(valPointer.Type().Elem(), 0, valPointer.Elem().Cap()))
return valPointer.Interface()
}
return a.value.Addr().Interface()
}
// Constraint returns the content for a where clause, and the args
// needed to execute it.
func (a *hasManyAssociation) Constraint() (string, []interface{}) {
tn := flect.Underscore(a.ownerName)
condition := fmt.Sprintf("%s_id = ?", tn)
if a.fkID != "" {
condition = fmt.Sprintf("%s = ?", a.fkID)
}
return condition, []interface{}{a.ownerID}
}
func (a *hasManyAssociation) OrderBy() string {
return a.orderBy
}
func (a *hasManyAssociation) AfterInterface() interface{} {
if a.value.Kind() == reflect.Ptr {
return a.value.Interface()
}
return a.value.Addr().Interface()
}
func (a *hasManyAssociation) AfterSetup() error {
ownerID := reflect.Indirect(reflect.ValueOf(a.owner)).FieldByName("ID").Interface()
v := a.value
if v.Kind() == reflect.Ptr {
v = v.Elem()
}
for i := 0; i < v.Len(); i++ {
fval := v.Index(i).FieldByName(a.ownerName + "ID")
if fval.CanSet() {
if n := nulls.New(fval.Interface()); n != nil {
fval.Set(reflect.ValueOf(n.Parse(ownerID)))
} else {
fval.Set(reflect.ValueOf(ownerID))
}
} else {
return fmt.Errorf("could not set '%s' in '%s'", ownerID, fval)
}
}
return nil
}
func (a *hasManyAssociation) AfterProcess() AssociationStatement {
v := a.value
if v.Kind() == reflect.Ptr {
v = v.Elem()
}
belongingIDFieldName := "ID"
ownerIDFieldName := "ID"
ownerID := reflect.Indirect(reflect.ValueOf(a.owner)).FieldByName(ownerIDFieldName).Interface()
var ids []interface{}
for i := 0; i < v.Len(); i++ {
id := v.Index(i).FieldByName(belongingIDFieldName).Interface()
if !IsZeroOfUnderlyingType(id) {
ids = append(ids, id)
}
}
if len(ids) == 0 {
return AssociationStatement{
Statement: "",
Args: []interface{}{},
}
}
fk := a.fkID
if fk == "" {
fk = flect.Underscore(a.ownerName) + "_id"
}
// This will be used to update all of our owned models' foreign keys to our ID.
ret := fmt.Sprintf("UPDATE %s SET %s = ? WHERE %s in (?);", a.tableName, fk, belongingIDFieldName)
update, args, err := sqlx.In(ret, ownerID, ids)
if err != nil {
return AssociationStatement{
Statement: "",
Args: []interface{}{},
}
}
return AssociationStatement{
Statement: update,
Args: args,
}
}