forked from russross/meddler
-
Notifications
You must be signed in to change notification settings - Fork 2
/
scan.go
576 lines (484 loc) · 16 KB
/
scan.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
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
package meddler
import (
"database/sql"
"fmt"
"log"
"reflect"
"strconv"
"strings"
"sync"
)
// the name of our struct tag
const tagName = "meddler"
// Database contains database-specific options.
// MySQL, PostgreSQL, and SQLite are provided for convenience.
// Setting Default to any of these lets you use the package-level convenience functions.
type Database struct {
Quote string // the quote character for table and column names
Placeholder string // the placeholder style to use in generated queries
UseReturningToGetID bool // use PostgreSQL-style RETURNING "ID" instead of calling sql.Result.LastInsertID
}
var MySQL = &Database{
Quote: "`",
Placeholder: "?",
UseReturningToGetID: false,
}
var PostgreSQL = &Database{
Quote: `"`,
Placeholder: "$1",
UseReturningToGetID: true,
}
var SQLite = &Database{
Quote: `"`,
Placeholder: "?",
UseReturningToGetID: false,
}
var Default = MySQL
func (d *Database) quoted(s string) string {
return d.Quote + s + d.Quote
}
func (d *Database) placeholder(n int) string {
return strings.Replace(d.Placeholder, "1", strconv.FormatInt(int64(n), 10), 1)
}
// Debug enables debug mode, where unused columns and struct fields will be logged
var Debug = true
type structField struct {
column string
index int
primaryKey bool
meddler Meddler
}
type structData struct {
columns []string
fields map[string]*structField
pk string
}
// cache reflection data
var fieldsCache = make(map[reflect.Type]*structData)
var fieldsCacheMutex sync.Mutex
// getFields gathers the list of columns from a struct using reflection.
func getFields(dstType reflect.Type) (*structData, error) {
fieldsCacheMutex.Lock()
defer fieldsCacheMutex.Unlock()
if result, present := fieldsCache[dstType]; present {
return result, nil
}
// make sure dst is a non-nil pointer to a struct
if dstType.Kind() != reflect.Ptr {
return nil, fmt.Errorf("meddler called with non-pointer destination %v", dstType)
}
structType := dstType.Elem()
if structType.Kind() != reflect.Struct {
return nil, fmt.Errorf("meddler called with pointer to non-struct %v", dstType)
}
// gather the list of fields in the struct
data := new(structData)
data.fields = make(map[string]*structField)
for i := 0; i < structType.NumField(); i++ {
f := structType.Field(i)
// skip non-exported fields
if f.PkgPath != "" {
continue
}
// examine the tag for metadata
tag := strings.Split(f.Tag.Get(tagName), ",")
// was this field marked for skipping?
if len(tag) > 0 && tag[0] == "-" {
continue
}
// default to the field name
name := f.Name
// the tag can override the field name
if len(tag) > 0 && tag[0] != "" {
name = tag[0]
}
// check for a meddler
var meddler Meddler = registry["identity"]
for j := 1; j < len(tag); j++ {
if tag[j] == "pk" {
if f.Type.Kind() == reflect.Ptr {
return nil, fmt.Errorf("meddler found field %s which is marked as the primary key but is a pointer", f.Name)
}
// make sure it is an int of some kind
switch f.Type.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
default:
return nil, fmt.Errorf("meddler found field %s which is marked as the primary key, but is not an integer type", f.Name)
}
if data.pk != "" {
return nil, fmt.Errorf("meddler found field %s which is marked as the primary key, but a primary key field was already found", f.Name)
}
data.pk = name
} else if m, present := registry[tag[j]]; present {
meddler = m
} else {
return nil, fmt.Errorf("meddler found field %s with meddler %s, but that meddler is not registered", f.Name, tag[j])
}
}
if _, present := data.fields[name]; present {
return nil, fmt.Errorf("meddler found multiple fields for column %s", name)
}
data.fields[name] = &structField{
column: name,
primaryKey: name == data.pk,
index: i,
meddler: meddler,
}
data.columns = append(data.columns, name)
}
fieldsCache[dstType] = data
return data, nil
}
// Columns returns a list of column names for its input struct.
func (d *Database) Columns(src interface{}, includePk bool) ([]string, error) {
data, err := getFields(reflect.TypeOf(src))
if err != nil {
return nil, err
}
var names []string
for _, elt := range data.columns {
if !includePk && elt == data.pk {
continue
}
names = append(names, elt)
}
return names, nil
}
// Columns using the Default Database type
func Columns(src interface{}, includePk bool) ([]string, error) {
return Default.Columns(src, includePk)
}
// ColumnsQuoted is similar to Columns, but it return the list of columns in the form:
// `column1`,`column2`,...
// using Quote as the quote character.
func (d *Database) ColumnsQuoted(src interface{}, includePk bool) (string, error) {
unquoted, err := Columns(src, includePk)
if err != nil {
return "", err
}
var parts []string
for _, elt := range unquoted {
parts = append(parts, d.quoted(elt))
}
return strings.Join(parts, ","), nil
}
// ColumnsQuoted using the Default Database type
func ColumnsQuoted(src interface{}, includePk bool) (string, error) {
return Default.ColumnsQuoted(src, includePk)
}
// PrimaryKey returns the name and value of the primary key field. The name
// is the empty string if there is not primary key field marked.
func (d *Database) PrimaryKey(src interface{}) (name string, pk int64, err error) {
data, err := getFields(reflect.TypeOf(src))
if err != nil {
return "", 0, err
}
if data.pk == "" {
return "", 0, nil
}
name = data.pk
field := reflect.ValueOf(src).Elem().Field(data.fields[name].index)
switch field.Type().Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
pk = field.Int()
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
pk = int64(field.Uint())
default:
return "", 0, fmt.Errorf("meddler found field %s which is marked as the primary key, but is not an integer type", name)
}
return name, pk, nil
}
// PrimaryKey using the Default Database type
func PrimaryKey(src interface{}) (name string, pk int64, err error) {
return Default.PrimaryKey(src)
}
// SetPrimaryKey sets the primary key field to the given int value.
func (d *Database) SetPrimaryKey(src interface{}, pk int64) error {
data, err := getFields(reflect.TypeOf(src))
if err != nil {
return err
}
if data.pk == "" {
return fmt.Errorf("meddler.SetPrimaryKey: no primary key field found")
}
field := reflect.ValueOf(src).Elem().Field(data.fields[data.pk].index)
switch field.Type().Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
field.SetInt(pk)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
field.SetUint(uint64(pk))
default:
return fmt.Errorf("meddler found field %s which is marked as the primary key, but is not an integer type", data.pk)
}
return nil
}
// SetPrimaryKey using the Default Database type
func SetPrimaryKey(src interface{}, pk int64) error {
return Default.SetPrimaryKey(src, pk)
}
// Values returns a list of PreWrite processed values suitable for
// use in an INSERT or UPDATE query. If includePk is false, the primary
// key field is omitted. The columns used are the same ones (in the same
// order) as returned by Columns.
func (d *Database) Values(src interface{}, includePk bool) ([]interface{}, error) {
columns, err := d.Columns(src, includePk)
if err != nil {
return nil, err
}
return d.SomeValues(src, columns)
}
// Values using the Default Database type
func Values(src interface{}, includePk bool) ([]interface{}, error) {
return Default.Values(src, includePk)
}
// SomeValues returns a list of PreWrite processed values suitable for
// use in an INSERT or UPDATE query. The columns used are the same ones (in
// the same order) as specified in the columns argument.
func (d *Database) SomeValues(src interface{}, columns []string) ([]interface{}, error) {
data, err := getFields(reflect.TypeOf(src))
if err != nil {
return nil, err
}
structVal := reflect.ValueOf(src).Elem()
var values []interface{}
for _, name := range columns {
field, present := data.fields[name]
if !present {
// write null to the database
values = append(values, nil)
if Debug {
log.Printf("meddler.SomeValues: column [%s] not found in struct", name)
}
continue
}
saveVal, err := field.meddler.PreWrite(structVal.Field(field.index).Interface())
if err != nil {
return nil, fmt.Errorf("meddler.SomeValues: PreWrite error on column [%s]: %v", name, err)
}
values = append(values, saveVal)
}
return values, nil
}
// SomeValues using the Default Database type
func SomeValues(src interface{}, columns []string) ([]interface{}, error) {
return Default.SomeValues(src, columns)
}
// Placeholders returns a list of placeholders suitable for an INSERT or UPDATE query.
// If includePk is false, the primary key field is omitted.
func (d *Database) Placeholders(src interface{}, includePk bool) ([]string, error) {
data, err := getFields(reflect.TypeOf(src))
if err != nil {
return nil, err
}
var placeholders []string
for _, name := range data.columns {
if !includePk && name == data.pk {
continue
}
ph := d.placeholder(len(placeholders) + 1)
placeholders = append(placeholders, ph)
}
return placeholders, nil
}
// Placeholders using the Default Database type
func Placeholders(src interface{}, includePk bool) ([]string, error) {
return Default.Placeholders(src, includePk)
}
// PlaceholdersString returns a list of placeholders suitable for an INSERT
// or UPDATE query in string form, e.g.:
// ?,?,?,?
// if includePk is false, the primary key field is omitted.
func (d *Database) PlaceholdersString(src interface{}, includePk bool) (string, error) {
lst, err := d.Placeholders(src, includePk)
if err != nil {
return "", err
}
return strings.Join(lst, ","), nil
}
// PlaceholdersString using the Default Database type
func PlaceholdersString(src interface{}, includePk bool) (string, error) {
return Default.PlaceholdersString(src, includePk)
}
// scan a single row of data into a struct.
func (d *Database) scanRow(data *structData, rows *sql.Rows, dst interface{}, columns []string) error {
// check if there is data waiting
if !rows.Next() {
if err := rows.Err(); err != nil {
return err
}
return sql.ErrNoRows
}
// get a list of targets
targets, err := d.Targets(dst, columns)
if err != nil {
return err
}
// perform the scan
if err := rows.Scan(targets...); err != nil {
return err
}
// post-process and copy the target values into the struct
if err := d.WriteTargets(dst, columns, targets); err != nil {
return err
}
return rows.Err()
}
// Targets returns a list of values suitable for handing to a
// Scan function in the sql package, complete with meddling. After
// the Scan is performed, the same values should be handed to
// WriteTargets to finalize the values and record them in the struct.
func (d *Database) Targets(dst interface{}, columns []string) ([]interface{}, error) {
data, err := getFields(reflect.TypeOf(dst))
if err != nil {
return nil, err
}
structVal := reflect.ValueOf(dst).Elem()
var targets []interface{}
for _, name := range columns {
if field, present := data.fields[name]; present {
fieldAddr := structVal.Field(field.index).Addr().Interface()
scanTarget, err := field.meddler.PreRead(fieldAddr)
if err != nil {
return nil, fmt.Errorf("meddler.Targets: PreRead error on column %s: %v", name, err)
}
targets = append(targets, scanTarget)
} else {
// no destination, so throw this away
targets = append(targets, new(interface{}))
if Debug {
log.Printf("meddler.Targets: column [%s] not found in struct %T", name, dst)
}
}
}
return targets, nil
}
// Targets using the Default Database type
func Targets(dst interface{}, columns []string) ([]interface{}, error) {
return Default.Targets(dst, columns)
}
// WriteTargets post-processes values with meddlers after a Scan from the
// sql package has been performed. The list of targets is normally produced
// by Targets.
func (d *Database) WriteTargets(dst interface{}, columns []string, targets []interface{}) error {
if len(columns) != len(targets) {
return fmt.Errorf("meddler.WriteTargets: mismatch in number of columns (%d) and targets (%d)",
len(columns), len(targets))
}
data, err := getFields(reflect.TypeOf(dst))
if err != nil {
return err
}
structVal := reflect.ValueOf(dst).Elem()
for i, name := range columns {
if field, present := data.fields[name]; present {
fieldAddr := structVal.Field(field.index).Addr().Interface()
err := field.meddler.PostRead(fieldAddr, targets[i])
if err != nil {
return fmt.Errorf("meddler.WriteTargets: PostRead error on column [%s]: %v", name, err)
}
} else {
// not destination, so throw this away
if Debug {
log.Printf("meddler.WriteTargets: column [%s] not found in struct %T", name, dst)
}
}
}
return nil
}
// WriteTargets using the Default Database type
func WriteTargets(dst interface{}, columns []string, targets []interface{}) error {
return Default.WriteTargets(dst, columns, targets)
}
// Scan scans a single sql result row into a struct.
// It leaves rows ready to be scanned again for the next row.
// Returns sql.ErrNoRows if there is no data to read.
func (d *Database) Scan(rows *sql.Rows, dst interface{}) error {
// get the list of struct fields
data, err := getFields(reflect.TypeOf(dst))
if err != nil {
return err
}
// get the sql columns
columns, err := rows.Columns()
if err != nil {
return err
}
return d.scanRow(data, rows, dst, columns)
}
// Scan using the Default Database type
func Scan(rows *sql.Rows, dst interface{}) error {
return Default.Scan(rows, dst)
}
// ScanRow scans a single sql result row into a struct.
// It reads exactly one result row and closes rows when finished.
// Returns sql.ErrNoRows if there is no result row.
func (d *Database) ScanRow(rows *sql.Rows, dst interface{}) error {
// make sure we always close rows
defer rows.Close()
if err := d.Scan(rows, dst); err != nil {
return err
}
if err := rows.Close(); err != nil {
return err
}
return nil
}
// ScanRow using the Default Database type
func ScanRow(rows *sql.Rows, dst interface{}) error {
return Default.ScanRow(rows, dst)
}
// ScanAll scans all sql result rows into a slice of structs.
// It reads all rows and closes rows when finished.
// dst should be a pointer to a slice of the appropriate type.
// The new results will be appended to any existing data in dst.
func (d *Database) ScanAll(rows *sql.Rows, dst interface{}) error {
// make sure we always close rows
defer rows.Close()
// make sure dst is an appropriate type
dstVal := reflect.ValueOf(dst)
if dstVal.Kind() != reflect.Ptr || dstVal.IsNil() {
return fmt.Errorf("ScanAll called with non-pointer destination: %T", dst)
}
sliceVal := dstVal.Elem()
if sliceVal.Kind() != reflect.Slice {
return fmt.Errorf("ScanAll called with pointer to non-slice: %T", dst)
}
ptrType := sliceVal.Type().Elem()
if ptrType.Kind() != reflect.Ptr {
return fmt.Errorf("ScanAll expects element to be pointers, found %T", dst)
}
eltType := ptrType.Elem()
if eltType.Kind() != reflect.Struct {
return fmt.Errorf("ScanAll expects element to be pointers to structs, found %T", dst)
}
// get the list of struct fields
data, err := getFields(ptrType)
if err != nil {
return err
}
// get the sql columns
columns, err := rows.Columns()
if err != nil {
return err
}
// gather the results
for {
// create a new element
eltVal := reflect.New(eltType)
elt := eltVal.Interface()
// scan it
if err := d.scanRow(data, rows, elt, columns); err != nil {
if err == sql.ErrNoRows {
return nil
}
return err
}
// add to the result slice
sliceVal.Set(reflect.Append(sliceVal, eltVal))
}
}
// ScanAll using the Default Database type
func ScanAll(rows *sql.Rows, dst interface{}) error {
return Default.ScanAll(rows, dst)
}