forked from gobuffalo/pop
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathmodel.go
More file actions
290 lines (248 loc) · 6.97 KB
/
model.go
File metadata and controls
290 lines (248 loc) · 6.97 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
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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
package pop
import (
"context"
"fmt"
"reflect"
"regexp"
"runtime"
"strings"
"time"
"github.com/gobuffalo/flect"
nflect "github.com/gobuffalo/flect/name"
"github.com/gofrs/uuid"
"github.com/ory/pop/v6/columns"
)
var nowFunc = time.Now
func ensuredCalledInsideInit() {
// If the call stack is deeper than 1024... we got bigger problems.
callers := [1024]uintptr{}
callersCount := runtime.Callers(0, callers[:])
frames := runtime.CallersFrames(callers[:callersCount])
// The `init()` function gets compiled to `path/to/pkg.init.0` where
// the final number varies.
re := regexp.MustCompile(`\.init\.\d+$`)
for {
frame, ok := frames.Next()
if !ok {
break
}
if re.Match([]byte(frame.Func.Name())) {
return
}
}
panic("caller init() not found in call stack, reached end of call stack")
}
// SetNowFunc allows an override of time.Now for customizing CreatedAt/UpdatedAt
func SetNowFunc(f func() time.Time) {
// From the Go spec:
// > the invocation of init functions—happens in a single goroutine, sequentially, one package at a time
// Since this function mutates a global variable, it should only be called inside `init()`.
ensuredCalledInsideInit()
nowFunc = f
}
// Value is the contents of a `Model`.
type Value interface{}
type modelIterable func(*Model) error
// Model is used throughout Pop to wrap the end user interface
// that is passed in to many functions.
type Model struct {
Value
ctx context.Context
As string
}
// NewModel returns a new model with the specified value and context.
func NewModel(v Value, ctx context.Context) *Model {
return &Model{Value: v, ctx: ctx}
}
// ID returns the ID of the Model. All models must have an `ID` field this is
// of type `int`,`int64` or of type `uuid.UUID`.
func (m *Model) ID() interface{} {
fbn, err := m.fieldByName("ID")
if err != nil {
return nil
}
if pkt, _ := m.PrimaryKeyType(); pkt == "UUID" {
return fbn.Interface().(uuid.UUID).String()
}
return fbn.Interface()
}
// IDField returns the name of the DB field used for the ID.
// By default, it will return "id".
func (m *Model) IDField() string {
modelType := reflect.TypeOf(m.Value)
// remove all indirections
for modelType.Kind() == reflect.Slice || modelType.Kind() == reflect.Ptr || modelType.Kind() == reflect.Array {
modelType = modelType.Elem()
}
if modelType.Kind() == reflect.String {
return "id"
}
field, ok := modelType.FieldByName("ID")
if !ok {
return "id"
}
dbField := field.Tag.Get("db")
if dbField == "" {
return "id"
}
return dbField
}
// PrimaryKeyType gives the primary key type of the `Model`.
func (m *Model) PrimaryKeyType() (string, error) {
fbn, err := m.fieldByName("ID")
if err != nil {
return "", fmt.Errorf("model %T is missing required field ID", m.Value)
}
return fbn.Type().Name(), nil
}
// TableNameAble interface allows for the customize table mapping
// between a name and the database. For example the value
// `User{}` will automatically map to "users". Implementing `TableNameAble`
// would allow this to change to be changed to whatever you would like.
type TableNameAble interface {
TableName() string
}
// TableNameAbleWithContext is equal to TableNameAble but will
// be passed the queries' context. Useful in cases where the
// table name depends on e.g.
type TableNameAbleWithContext interface {
TableName(ctx context.Context) string
}
// TableName returns the corresponding name of the underlying database table
// for a given `Model`. See also `TableNameAble` to change the default name of the table.
func (m *Model) TableName() string {
if s, ok := m.Value.(string); ok {
return s
}
if n, ok := m.Value.(TableNameAble); ok {
return n.TableName()
}
if n, ok := m.Value.(TableNameAbleWithContext); ok {
if m.ctx == nil {
m.ctx = context.TODO()
}
return n.TableName(m.ctx)
}
return m.typeName(reflect.TypeOf(m.Value))
}
func (m *Model) Columns() columns.Columns {
return columns.ForStructWithAlias(m.Value, m.TableName(), m.As, m.IDField())
}
func (m *Model) typeName(t reflect.Type) (name string) {
if t.Kind() == reflect.Ptr {
t = t.Elem()
}
switch t.Kind() {
case reflect.Slice, reflect.Array:
el := t.Elem()
if el.Kind() == reflect.Ptr {
el = el.Elem()
}
// validates if the elem of slice or array implements TableNameAble interface.
var tableNameAble *TableNameAble
if el.Implements(reflect.TypeOf(tableNameAble).Elem()) {
v := reflect.New(el)
out := v.MethodByName("TableName").Call([]reflect.Value{})
return out[0].String()
}
// validates if the elem of slice or array implements TableNameAbleWithContext interface.
var tableNameAbleWithContext *TableNameAbleWithContext
if el.Implements(reflect.TypeOf(tableNameAbleWithContext).Elem()) {
v := reflect.New(el)
out := v.MethodByName("TableName").Call([]reflect.Value{reflect.ValueOf(m.ctx)})
return out[0].String()
// We do not want to cache contextualized TableNames because that would break
// the contextualization.
}
return nflect.Tableize(el.Name())
default:
return nflect.Tableize(t.Name())
}
}
func (m *Model) fieldByName(s string) (reflect.Value, error) {
el := reflect.ValueOf(m.Value).Elem()
fbn := el.FieldByName(s)
if !fbn.IsValid() {
return fbn, fmt.Errorf("model does not have a field named %s", s)
}
return fbn, nil
}
func (m *Model) associationName() string {
tn := flect.Singularize(m.TableName())
return fmt.Sprintf("%s_id", tn)
}
func (m *Model) setID(i interface{}) {
fbn, err := m.fieldByName("ID")
if err == nil {
v := reflect.ValueOf(i)
switch fbn.Kind() {
case reflect.Int, reflect.Int64:
fbn.SetInt(v.Int())
default:
fbn.Set(reflect.ValueOf(i))
}
}
}
func (m *Model) setCreatedAt(now time.Time) {
fbn, err := m.fieldByName("CreatedAt")
if err == nil {
v := fbn.Interface()
if !IsZeroOfUnderlyingType(v) {
// Do not override already set CreatedAt
return
}
switch v.(type) {
case int, int64:
fbn.SetInt(now.Unix())
default:
fbn.Set(reflect.ValueOf(now))
}
}
}
func (m *Model) setUpdatedAt(now time.Time) {
fbn, err := m.fieldByName("UpdatedAt")
if err == nil {
v := fbn.Interface()
switch v.(type) {
case int, int64:
fbn.SetInt(now.Unix())
default:
fbn.Set(reflect.ValueOf(now))
}
}
}
func (m *Model) WhereID() string {
return fmt.Sprintf("%s.%s = ?", m.Alias(), m.IDField())
}
func (m *Model) Alias() string {
as := m.As
if as == "" {
as = strings.ReplaceAll(m.TableName(), ".", "_")
}
return as
}
func (m *Model) WhereNamedID() string {
return fmt.Sprintf("%s.%s = :%s", m.Alias(), m.IDField(), m.IDField())
}
func (m *Model) isSlice() bool {
v := reflect.Indirect(reflect.ValueOf(m.Value))
return v.Kind() == reflect.Slice || v.Kind() == reflect.Array
}
func (m *Model) iterate(fn modelIterable) error {
if m.isSlice() {
v := reflect.Indirect(reflect.ValueOf(m.Value))
for i := 0; i < v.Len(); i++ {
val := v.Index(i)
newModel := &Model{
Value: val.Addr().Interface(),
ctx: m.ctx,
}
err := fn(newModel)
if err != nil {
return err
}
}
return nil
}
return fn(m)
}