forked from jmoiron/modl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
modl.go
375 lines (310 loc) · 8.44 KB
/
modl.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
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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
package modl
// Changes Copyright 2013 Jason Moiron. Original Gorp code
// Copyright 2012 James Cooper. All rights reserved.
//
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
//
// Source code and project home:
// https://github.com/jmoiron/modl
import (
"database/sql"
"fmt"
"reflect"
)
// NoKeysErr is a special error type returned when modl's CRUD helpers are
// used on tables which have not been set up with a primary key.
type NoKeysErr struct {
Table *TableMap
}
// Error returns the string representation of a NoKeysError.
func (n NoKeysErr) Error() string {
return fmt.Sprintf("Could not find keys for table %v", n.Table)
}
const versFieldConst = "[modl_ver_field]"
// OptimisticLockError is returned by Update() or Delete() if the
// struct being modified has a Version field and the value is not equal to
// the current value in the database
type OptimisticLockError struct {
// Table name where the lock error occurred
TableName string
// Primary key values of the row being updated/deleted
Keys []interface{}
// true if a row was found with those keys, indicating the
// LocalVersion is stale. false if no value was found with those
// keys, suggesting the row has been deleted since loaded, or
// was never inserted to begin with
RowExists bool
// Version value on the struct passed to Update/Delete. This value is
// out of sync with the database.
LocalVersion int64
}
// Error returns a description of the cause of the lock error
func (e OptimisticLockError) Error() string {
if e.RowExists {
return fmt.Sprintf("OptimisticLockError table=%s keys=%v out of date version=%d", e.TableName, e.Keys, e.LocalVersion)
}
return fmt.Sprintf("OptimisticLockError no row found for table=%s keys=%v", e.TableName, e.Keys)
}
// A bindPlan saves a query type (insert, get, updated, delete) so it doesn't
// have to be re-created every time it's executed.
type bindPlan struct {
query string
argFields []string
keyFields []string
versField string
autoIncrIdx int
}
func (plan bindPlan) createBindInstance(elem reflect.Value) bindInstance {
bi := bindInstance{query: plan.query, autoIncrIdx: plan.autoIncrIdx, versField: plan.versField}
if plan.versField != "" {
bi.existingVersion = elem.FieldByName(plan.versField).Int()
}
for i := 0; i < len(plan.argFields); i++ {
k := plan.argFields[i]
if k == versFieldConst {
newVer := bi.existingVersion + 1
bi.args = append(bi.args, newVer)
if bi.existingVersion == 0 {
elem.FieldByName(plan.versField).SetInt(int64(newVer))
}
} else {
val := elem.FieldByName(k).Interface()
bi.args = append(bi.args, val)
}
}
for i := 0; i < len(plan.keyFields); i++ {
k := plan.keyFields[i]
val := elem.FieldByName(k).Interface()
bi.keys = append(bi.keys, val)
}
return bi
}
type bindInstance struct {
query string
args []interface{}
keys []interface{}
existingVersion int64
versField string
autoIncrIdx int
}
// SqlExecutor exposes modl operations that can be run from Pre/Post
// hooks. This hides whether the current operation that triggered the
// hook is in a transaction.
//
// See the DbMap function docs for each of the functions below for more
// information.
type SqlExecutor interface {
Get(dest interface{}, keys ...interface{}) error
Insert(list ...interface{}) error
Update(list ...interface{}) (int64, error)
Delete(list ...interface{}) (int64, error)
Exec(query string, args ...interface{}) (sql.Result, error)
Select(dest interface{}, query string, args ...interface{}) error
SelectOne(dest interface{}, query string, args ...interface{}) error
handle() handle
}
// Compile-time check that DbMap and Transaction implement the SqlExecutor
// interface.
var (
_ SqlExecutor = &DbMap{}
_ SqlExecutor = &Transaction{}
)
///////////////
func hookedget(m *DbMap, e SqlExecutor, dest interface{}, query string, args ...interface{}) error {
err := e.handle().Get(dest, query, args...)
if err != nil {
return err
}
table := m.TableFor(dest)
if table != nil && table.CanPostGet {
err = dest.(PostGetter).PostGet(e)
if err != nil {
return err
}
}
return nil
}
func hookedselect(m *DbMap, e SqlExecutor, dest interface{}, query string, args ...interface{}) error {
err := e.handle().Select(dest, query, args...)
if err != nil {
return err
}
// select can use arbitrary structs for join queries, so we needn't find a table
table := m.TableFor(dest)
if table != nil && table.CanPostGet {
var x interface{}
v := reflect.ValueOf(dest)
if v.Kind() == reflect.Ptr {
v = reflect.Indirect(v)
}
l := v.Len()
for i := 0; i < l; i++ {
x = v.Index(i).Interface()
err = x.(PostGetter).PostGet(e)
if err != nil {
return err
}
}
}
return nil
}
func get(m *DbMap, e SqlExecutor, dest interface{}, keys ...interface{}) error {
table := m.TableFor(dest)
if table == nil {
return fmt.Errorf("could not find table for %v", dest)
}
if len(table.Keys) < 1 {
return &NoKeysErr{table}
}
plan := table.bindGet()
err := e.handle().Get(dest, plan.query, keys...)
if err != nil {
return err
}
if table.CanPostGet {
err = dest.(PostGetter).PostGet(e)
if err != nil {
return err
}
}
return nil
}
func deletes(m *DbMap, e SqlExecutor, list ...interface{}) (int64, error) {
var err error
var table *TableMap
var elem reflect.Value
var count int64
for _, ptr := range list {
table, elem, err = tableForPointer(m, ptr, true)
if err != nil {
return -1, err
}
if table.CanPreDelete {
err = ptr.(PreDeleter).PreDelete(e)
if err != nil {
return -1, err
}
}
bi := table.bindDelete(elem)
res, err := e.Exec(bi.query, bi.args...)
if err != nil {
return -1, err
}
rows, err := res.RowsAffected()
if err != nil {
return -1, err
}
if rows == 0 && bi.existingVersion > 0 {
return lockError(m, e, table.TableName, bi.existingVersion, elem, bi.keys...)
}
count += rows
if table.CanPostDelete {
err = ptr.(PostDeleter).PostDelete(e)
if err != nil {
return -1, err
}
}
}
return count, nil
}
func update(m *DbMap, e SqlExecutor, list ...interface{}) (int64, error) {
var err error
var table *TableMap
var elem reflect.Value
var count int64
for _, ptr := range list {
table, elem, err = tableForPointer(m, ptr, true)
if err != nil {
return -1, err
}
if table.CanPreUpdate {
err = ptr.(PreUpdater).PreUpdate(e)
if err != nil {
return -1, err
}
}
bi := table.bindUpdate(elem)
if err != nil {
return -1, err
}
res, err := e.Exec(bi.query, bi.args...)
if err != nil {
return -1, err
}
rows, err := res.RowsAffected()
if err != nil {
return -1, err
}
if rows == 0 && bi.existingVersion > 0 {
return lockError(m, e, table.TableName,
bi.existingVersion, elem, bi.keys...)
}
if bi.versField != "" {
elem.FieldByName(bi.versField).SetInt(bi.existingVersion + 1)
}
count += rows
if table.CanPostUpdate {
err = ptr.(PostUpdater).PostUpdate(e)
if err != nil {
return -1, err
}
}
}
return count, nil
}
func insert(m *DbMap, e SqlExecutor, list ...interface{}) error {
var err error
var table *TableMap
var elem reflect.Value
for _, ptr := range list {
table, elem, err = tableForPointer(m, ptr, false)
if err != nil {
return err
}
if table.CanPreInsert {
err = ptr.(PreInserter).PreInsert(e)
if err != nil {
return err
}
}
bi := table.bindInsert(elem)
if bi.autoIncrIdx > -1 {
id, err := m.Dialect.InsertAutoIncr(e, bi.query, bi.args...)
if err != nil {
return err
}
f := elem.Field(bi.autoIncrIdx)
k := f.Kind()
if (k == reflect.Int) || (k == reflect.Int16) || (k == reflect.Int32) || (k == reflect.Int64) {
f.SetInt(id)
} else {
return fmt.Errorf("modl: Cannot set autoincrement value on non-Int field. SQL=%s autoIncrIdx=%d", bi.query, bi.autoIncrIdx)
}
} else {
_, err := e.Exec(bi.query, bi.args...)
if err != nil {
return err
}
}
if table.CanPostInsert {
err = ptr.(PostInserter).PostInsert(e)
if err != nil {
return err
}
}
}
return nil
}
func lockError(m *DbMap, e SqlExecutor, tableName string, existingVer int64, elem reflect.Value, keys ...interface{}) (int64, error) {
dest := reflect.New(elem.Type()).Interface()
err := get(m, e, dest, keys...)
if err != nil {
return -1, err
}
ole := OptimisticLockError{tableName, keys, true, existingVer}
if dest == nil {
ole.RowExists = false
}
return -1, ole
}