-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmarshall.go
More file actions
817 lines (779 loc) · 26.7 KB
/
Copy pathmarshall.go
File metadata and controls
817 lines (779 loc) · 26.7 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
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
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
package SqlMarshall
import (
"database/sql"
"database/sql/driver"
"errors"
"fmt"
"reflect"
"regexp"
"strconv"
"strings"
"time"
"github.com/jmoiron/sqlx"
"github.com/jmoiron/sqlx/reflectx"
)
//ErrBadTableName used in case of illegal characters in the table definition in GetTableLength
var ErrBadTableName = errors.New("The table name inputted does not contain legal characters")
var errNilPtr = errors.New("destination pointer is nil") // embedded in descriptive error
// UnMarshall copies the values from a database structure into an internal representation structure
// using the annotations on the database structure to indicate which field to copy to. This maps
// null fields from the database (stored in the sql.NullString... structures) into an appropriate null value.
func UnMarshall(source interface{}, dest interface{}) error {
// We need both the Value (for the source values) and the Type (to get structure and annotations) of the source.
sourceValue := reflect.Indirect(reflect.ValueOf(source))
sourceType := sourceValue.Type()
// For the dest we just need the Value structure.
destValue := reflect.ValueOf(dest)
// Make sure we have a pointer to the structure
if destValue.Kind() != reflect.Ptr {
return fmt.Errorf("Destination is not a pointer")
}
// Dereference the pointer to get to the raw type
destValue = destValue.Elem()
// Sanity check to make sure we are working with structures
if sourceType.Kind() != reflect.Struct {
return fmt.Errorf("Source is not a struct")
}
if destValue.Kind() != reflect.Struct {
return fmt.Errorf("Destination is not a pointer to a struct")
}
// We have a structure, so iterate through all the fields in the structure
for fieldNum := 0; fieldNum < sourceType.NumField(); fieldNum++ {
// For the source field we need the Value and the Type
fieldValue := sourceValue.Field(fieldNum)
fieldType := sourceType.Field(fieldNum)
// Are we using an alternate name to save into or the same name
mappedName, hasMappedName := fieldType.Tag.Lookup("map")
if !hasMappedName {
mappedName = fieldType.Name
}
// Check to see if they are indexing the field
// This will be indicated by a mapped name like NAICSCode[1]
// in which case we need to parse out the index.
// NOTE: we don't require the closing ] but we need to make sure that the index is a valid number.
strslice := strings.Split(mappedName, "[")
// Assume we don't have an index
hasindex := false
sliceindex := 0
// Unless we actually have something after the []
if len(strslice) > 1 {
// Get rid of any trailing ] and parse the number as an integer
piece2 := strings.Split(strslice[1], "]")
newspot, err := strconv.Atoi(piece2[0])
// As long as it parses correctly, we will use that index and clean up the mapped name
if err == nil {
sliceindex = newspot
hasindex = true
mappedName = strslice[0]
}
}
// Find any default custom nil value.
nullDefault, hasNullDefault := fieldType.Tag.Lookup("null")
// Figure out our source value type and look for the special cases of the special sql null items
sourceInterface := fieldValue.Interface()
// Make sure it is something we can actually manipulate
if !fieldValue.IsValid() {
return fmt.Errorf("Field %+v is not valid", mappedName)
}
switch sourceInterface.(type) {
case sql.NullString:
// Default is "" unless they override
if sourceInterface.(sql.NullString).Valid {
sourceInterface = sourceInterface.(sql.NullString).String
} else if hasNullDefault {
sourceInterface = nullDefault
} else {
sourceInterface = ""
}
// Commented out because a NullBool really doesn't make any sense
// case sql.NullBool:
// // Default is False unless they override with the string "true"
// if sourceInterface.(sql.NullString).Valid {
// sourceInterface = sourceInterface.(sql.NullBool).Bool
// } else if strings.EqualFold(nullDefault, "true") {
// sourceInterface = true
// } else {
// sourceInterface = false
// }
case sql.NullInt64:
// Default is 0 unless they override with a value
if sourceInterface.(sql.NullInt64).Valid {
sourceInterface = sourceInterface.(sql.NullInt64).Int64
} else {
sourceInterface = 0
// If they gave us a null value, make sure it parses as a number, otherwise we will
// stick with the default override.
if hasNullDefault {
altValue, err := strconv.ParseInt(nullDefault, 10, 64)
if err == nil {
sourceInterface = altValue
}
}
}
case sql.NullFloat64:
// Default is 0.0 unless they override with a value
if sourceInterface.(sql.NullFloat64).Valid {
sourceInterface = sourceInterface.(sql.NullFloat64).Float64
} else {
// If they gave us a null value, make sure it parses as a float, otherwise we will
// stick with the default override.
sourceInterface = 0.0
if hasNullDefault {
altValue, err := strconv.ParseFloat(nullDefault, 64)
if err == nil {
sourceInterface = altValue
}
}
}
}
//
// Figure out what we are going to write to
//
destFieldValue, err := FieldByPath(destValue, mappedName)
if err != nil {
return err
}
if !destFieldValue.IsValid() {
return fmt.Errorf("Mapped Field %+v is not valid for %+v", mappedName, fieldType.Name)
}
// We have the output field we want to write to.
// Check to see if we are going into an array for the output
if hasindex && (destFieldValue.Kind() == reflect.Array || destFieldValue.Kind() == reflect.Slice) {
// Make sure that the array index is in bounds
if sliceindex >= destFieldValue.Len() {
if destFieldValue.Kind() == reflect.Array {
// it is an array, and what they gave us is out of bounds so we have to generate an error
return fmt.Errorf("Mapped Field %+v[%+v] is out of bounds (>%+v) for %+v",
mappedName, sliceindex, destFieldValue.Len(), fieldType.Name)
}
zeroElem := reflect.Zero(destFieldValue.Type().Elem())
// We have a slice, we need to extend the slice
for destFieldValue.Len() <= sliceindex {
destFieldValue.Set(reflect.Append(destFieldValue, zeroElem))
}
}
destFieldValue = destFieldValue.Index(sliceindex)
}
err = CopyInterface(destFieldValue, sourceInterface)
if err != nil {
return err
}
}
return nil
}
// FieldByPath returns the struct field with the given path
// It returns the zero Value if no field was found.
// Note that if there is no period in the name then this is exactly
// the same as FieldMyName (except it doesn't panic)
func FieldByPath(v reflect.Value, name string) (reflect.Value, error) {
for name != "" {
// Avoid getting a Panic in FieldByName by checking to make sure we have a structure to deal with
if v.Kind() != reflect.Struct {
return reflect.Value{}, fmt.Errorf("FieldByPath expected %+v to be a structure to find field %+v", v, name)
}
// Split off everything after the period (if there actually is one)
strslice := strings.SplitN(name, ".", 2)
// And get the Field for the first portion
v = v.FieldByName(strslice[0])
// Use what is left over after the . to repeat the process
name = ""
if len(strslice) > 1 && v.IsValid() {
name = strslice[1]
}
}
return v, nil
}
// Marshall copies the values to a database structure from an internal representation structure
// using the annotations on the database structure to indicate which field to copy to. This maps
// null fields from the database (stored in the sql.NullString... structures) into an appropriate null value.
func Marshall(source interface{}, dest interface{}) error {
// For the source we just need the Value structure.
sourceValue := reflect.Indirect(reflect.ValueOf(source))
// For the dest we need both the Value (for the source values) and the Type (to get structure and annotations) of the source.
destValue := reflect.ValueOf(dest)
// Make sure we have a pointer to the structure
if destValue.Kind() != reflect.Ptr {
return fmt.Errorf("Destination is not a pointer")
}
// Derefence the pointer to get to the raw type
destValue = destValue.Elem()
destType := destValue.Type()
// Sanity check to make sure we are working with structures
if sourceValue.Kind() != reflect.Struct {
return fmt.Errorf("Source is not a struct")
}
// Remember we already dereferenced the pointer, so the warning is different
if destType.Kind() != reflect.Struct {
return fmt.Errorf("Destination is not a pointer to a struct")
}
// We have a structure, so iterate through all the fields in the destination type structure
// because that structure has all of the annotations on it
for fieldNum := 0; fieldNum < destType.NumField(); fieldNum++ {
// For the dest field we need the Value and the Type
fieldValue := destValue.Field(fieldNum)
fieldType := destType.Field(fieldNum)
// Are we using an alternate name to save into or the same name
mappedName, hasMappedName := fieldType.Tag.Lookup("map")
if !hasMappedName {
mappedName = fieldType.Name
}
// Check to see if they are indexing the field
// This will be indicated by a mapped name like NAICSCode[1]
// in which case we need to parse out the index.
// NOTE: we don't require the closing ] but we need to make sure that the index is a valid number.
strslice := strings.Split(mappedName, "[")
// Assume we don't have an index
hasindex := false
sliceindex := 0
// Unless we actually have something after the []
if len(strslice) > 1 {
// Get rid of any trailing ] and parse the number as an integer
piece2 := strings.Split(strslice[1], "]")
newspot, err := strconv.Atoi(piece2[0])
// As long as it parses correctly, we will use that index and clean up the mapped name
if err == nil {
sliceindex = newspot
hasindex = true
mappedName = strslice[0]
}
}
// Find any default custom null value.
nullDefault, hasNullDefault := fieldType.Tag.Lookup("null")
//
// Figure out what the source value is
//
srcFieldValue, err := FieldByPath(sourceValue, mappedName)
if err != nil {
return err
}
if !srcFieldValue.IsValid() {
return fmt.Errorf("Mapped Field %+v is not valid for %+v", mappedName, fieldType.Name)
}
// We have the output field we want to write to.
// Check to see if we are going into an array for the output
if hasindex && (srcFieldValue.Kind() == reflect.Array || srcFieldValue.Kind() == reflect.Slice) {
// Make sure that the array index is in bounds
if sliceindex >= srcFieldValue.Len() {
srcFieldValue = reflect.Zero(srcFieldValue.Type().Elem())
} else {
srcFieldValue = srcFieldValue.Index(sliceindex)
}
}
// Make sure it is something we can actually manipulate
if !srcFieldValue.IsValid() {
return fmt.Errorf("Source Field %+v is not valid", mappedName)
}
// We have the source value, figure out if we have to do something special for the output field
// to handle the special sql null items
destInterface := fieldValue.Interface()
switch destInterface.(type) {
case sql.NullString:
String := asString(srcFieldValue.Interface())
if !hasNullDefault {
nullDefault = ""
}
Valid := (String != nullDefault)
CopyInterface(fieldValue.FieldByName("String"), String)
CopyInterface(fieldValue.FieldByName("Valid"), Valid)
// Commented out because a NullBool makes no sense
// case sql.NullBool:
// // Default is False unless they override with the string "true"
// bool := false
// defaultbool := false
// if sourceInterface.(sql.NullString).Valid {
// sourceInterface = sourceInterface.(sql.NullBool).Bool
// } else if strings.EqualFold(nullDefault, "true") {
// sourceInterface = true
// } else {
// sourceInterface = false
// }
case sql.NullInt64:
// Default is 0 unless they override with a value
Int64 := srcFieldValue.Int()
nullInt64 := int64(0)
if hasNullDefault {
altValue, err := strconv.ParseInt(nullDefault, 10, 64)
if err == nil {
nullInt64 = altValue
}
}
Valid := (Int64 != nullInt64)
CopyInterface(fieldValue.FieldByName("Int64"), Int64)
CopyInterface(fieldValue.FieldByName("Valid"), Valid)
case sql.NullFloat64:
// Default is 0.0 unless they override with a value
Float64 := srcFieldValue.Float()
nullFloat64 := float64(0.0)
if hasNullDefault {
altValue, err := strconv.ParseFloat(nullDefault, 64)
if err == nil {
nullFloat64 = altValue
}
}
Valid := (Float64 != nullFloat64)
CopyInterface(fieldValue.FieldByName("Float64"), Float64)
CopyInterface(fieldValue.FieldByName("Valid"), Valid)
default:
err := CopyInterface(fieldValue, srcFieldValue.Interface())
if err != nil {
return err
}
}
}
return nil
}
// Query executes a query on the database for a single record into a database template and then
// marshalls the result into a data interface.
// If no records are found for the query, sql.ErrNoRows is returned
//
func Query(db *sqlx.DB, query string, dbTemplate interface{}, data interface{}, args ...interface{}) (err error) {
var rows *sqlx.Rows
rows, err = db.Queryx(query, args...)
if err != nil {
return
}
// Close off the rows when we are done (since we may not have read to the end of the list)
defer rows.Close()
// If we didn't get any rows, let them know
if !rows.Next() {
err = sql.ErrNoRows
}
if err == nil {
// Scan only the first result into our database template
err = rows.StructScan(dbTemplate)
if err == nil {
// If that works, then UnMarshall the results into the program template
err = UnMarshall(dbTemplate, data)
}
}
return
}
// VerifySQLTableName checks for potential SQL injection errors by confirming that the
// table name does not contain anything but alpha numeric and underscore characters
//
func VerifySQLTableName(tableName string) (err error) {
err = nil
// The name of the table that they are going to use must not have anything that
// could cause a SQL Injection error
tableRegex := regexp.MustCompile(`^[A-Za-z0-9_\.]+$`)
if !tableRegex.MatchString(tableName) {
err = ErrBadTableName
}
return
}
// InsertRecord allows you to insert a new record into a table respecting nulls
func InsertRecord(db *sqlx.DB, tableName string, record interface{}) (sql.Result, error) {
// First check for any potential SQL Injection
err := VerifySQLTableName(tableName)
if err != nil {
return nil, err
}
sqlStr := "INSERT INTO " + tableName + " ("
valStr := ""
extra := ""
args := []interface{}{}
// We need both the Value (for the source values) and the Type (to get structure and annotations) of the source.
recordValue := reflect.Indirect(reflect.ValueOf(record))
recordType := recordValue.Type()
// Sanity check to make sure we are working with structures
if recordType.Kind() != reflect.Struct {
return nil, fmt.Errorf("record is not a struct")
}
// Use the standard mapper that pulls out the database mappings based on the db annotations in the structure
mapper := db.Mapper
typemap := mapper.TypeMap(recordValue.Type())
topLevel := typemap.Tree
// Iterate through all the members of the structure.
for _, fieldInfo := range topLevel.Children {
if fieldInfo == nil {
continue
}
addfield := false
field := fieldInfo.Name
// See if this field is an autoincrement field. If so, we just ignore and don't add it
_, hasAI := fieldInfo.Options["ai"]
if hasAI {
continue
}
// Get the value for this field
val := reflectx.FieldByIndexes(recordValue, fieldInfo.Index)
// Check to see if we are dealing with one of the SQL null structures
if val.Kind() == reflect.Struct {
fieldInterface := val.Interface()
switch fieldInterface.(type) {
case sql.NullString:
if fieldInterface.(sql.NullString).Valid {
addfield = true
val = reflect.ValueOf(fieldInterface.(sql.NullString).String)
}
case sql.NullInt64:
if fieldInterface.(sql.NullInt64).Valid {
addfield = true
val = reflect.ValueOf(fieldInterface.(sql.NullInt64).Int64)
}
case sql.NullFloat64:
if fieldInterface.(sql.NullFloat64).Valid {
addfield = true
val = reflect.ValueOf(fieldInterface.(sql.NullFloat64).Float64)
}
default:
addfield = true
}
} else {
addfield = true
}
// If this is a field we know how to handle with the database, then we can add it to the list of fields in the SQL
if addfield {
sqlStr = sqlStr + extra + field
valStr = valStr + extra + "?"
extra = ","
args = append(args, val.Interface())
}
}
// If we get here and the extra flag is not blank was set, it indicates that we had added at least one field to the
// structure to save. We can no generate the query and execute it.
if len(extra) > 0 {
sqlStr = sqlStr + ") VALUES (" + valStr + ")"
return db.Exec(sqlStr, args...)
}
// Apparently we had nothing to do, so just return quietly
return nil, nil
}
// UpdateRecord allows you to update an existing record in the database
func UpdateRecord(db *sqlx.DB, tableName string, record interface{}) (sql.Result, error) {
// First check for any potential SQL Injection
err := VerifySQLTableName(tableName)
if err != nil {
return nil, err
}
sqlStr := "UPDATE " + tableName + " SET "
extra := ""
where := ""
var whereval interface{}
args := []interface{}{}
// We need both the Value (for the source values) and the Type (to get structure and annotations) of the source.
recordValue := reflect.Indirect(reflect.ValueOf(record))
recordType := recordValue.Type()
// Sanity check to make sure we are working with structures
if recordType.Kind() != reflect.Struct {
return nil, fmt.Errorf("record is not a struct")
}
// Use the standard mapper that pulls out the database mappings based on the db annotations in the structure
mapper := db.Mapper
typemap := mapper.TypeMap(recordValue.Type())
topLevel := typemap.Tree
// Iterate through all the top level fields in the structure
for _, fieldInfo := range topLevel.Children {
if fieldInfo == nil {
continue
}
addfield := false
field := fieldInfo.Name
val := reflectx.FieldByIndexes(recordValue, fieldInfo.Index)
if val.Kind() == reflect.Struct {
fieldInterface := val.Interface()
switch fieldInterface.(type) {
case sql.NullString:
if fieldInterface.(sql.NullString).Valid {
addfield = true
val = reflect.ValueOf(fieldInterface.(sql.NullString).String)
}
case sql.NullInt64:
if fieldInterface.(sql.NullInt64).Valid {
addfield = true
val = reflect.ValueOf(fieldInterface.(sql.NullInt64).Int64)
}
case sql.NullFloat64:
if fieldInterface.(sql.NullFloat64).Valid {
addfield = true
val = reflect.ValueOf(fieldInterface.(sql.NullFloat64).Float64)
}
default:
addfield = true
}
} else {
addfield = true
}
// See if this field is an autoincrement field. If so, then it is the key we are matching on
_, hasAI := fieldInfo.Options["ai"]
_, hasRO := fieldInfo.Options["ro"]
// If this is a read only field, don't update it in the database
if hasRO {
addfield = false
}
if hasAI {
where = " WHERE " + field + "=?"
whereval = val.Interface()
// If this is a field we know how to handle with the database, then we can add it to the list of fields in the SQL
} else if addfield {
sqlStr = sqlStr + extra + field + "=?"
extra = ","
args = append(args, val.Interface())
}
}
// If we get here and the extra flag is not blank was set, it indicates that we had added at least one field to the
// structure to save. We can no generate the query and execute it.
if len(extra) > 0 {
sqlStr = sqlStr + where
args = append(args, whereval)
return db.Exec(sqlStr, args...)
}
// Apparently we had nothing to do, so just return quietly
return nil, nil
}
// MarshallInsertRecord inserts a record of any type into the database and returns the insertId from
// that record if it succeeds or any errors if it fails
// For the dbTemplate you must pass in an empty structure by address to allow the data to be marshalled
//
func MarshallInsertRecord(db *sqlx.DB, table string, data interface{}, dbTemplate interface{}) (resID int64, err error) {
// Default id returned is -1
resID = int64(0)
// Convert the data to a format the database likes
err = Marshall(data, dbTemplate)
if err != nil {
return
}
// Attempt to insert into the database
var res sql.Result
res, err = InsertRecord(db, table, dbTemplate)
if err != nil {
return
}
// If we succeeded, get the id of the last inserted record
resID, err = res.LastInsertId()
return
}
// MarshallUpdateRecord finds the record based on the table name and the autoIncrementing key. NOTE: Whatever structure
// is inserted into the table, the incrementing key must be the ONLY incrementing key in the table and it must be the same
// as the record you are hoping to update
//
func MarshallUpdateRecord(db *sqlx.DB, table string, data interface{}, dbTemplate interface{}) (resID int64, err error) {
// Default id returned is -1
resID = int64(0)
// Convert the data to a format the database likes
err = Marshall(data, dbTemplate)
if err != nil {
return
}
// Attempt to insert into the database
var res sql.Result
res, err = UpdateRecord(db, table, dbTemplate)
if err != nil {
return
}
// If we succeeded, get the id of the last inserted record
resID, err = res.LastInsertId()
return
}
//***************************************************************************************
//
// CopyInterface is a copy of convertAssign from the sql package
// It copies a value from a src to a destination interface converting types as appropriate.
// Ideally we would want to have this interface exported.. but the Powers-that-be decided
// to keep it private so we have to clone it here.
func CopyInterface(destValue reflect.Value, src interface{}) error {
// Common cases, without reflect.
destInterface := destValue.Interface()
switch srcType := src.(type) {
case string:
switch d := destInterface.(type) {
case *string:
if d == nil {
return errNilPtr
}
*d = srcType
return nil
case *[]byte:
if d == nil {
return errNilPtr
}
*d = []byte(srcType)
return nil
}
case []byte:
switch d := destInterface.(type) {
case *string:
if d == nil {
return errNilPtr
}
*d = string(srcType)
return nil
case *interface{}:
if d == nil {
return errNilPtr
}
*d = cloneBytes(srcType)
return nil
case *[]byte:
if d == nil {
return errNilPtr
}
*d = cloneBytes(srcType)
return nil
}
case time.Time:
switch d := destInterface.(type) {
case *string:
*d = srcType.Format(time.RFC3339Nano)
return nil
case *[]byte:
if d == nil {
return errNilPtr
}
*d = []byte(srcType.Format(time.RFC3339Nano))
return nil
}
case nil:
switch d := destInterface.(type) {
case *interface{}:
if d == nil {
return errNilPtr
}
*d = nil
return nil
case *[]byte:
if d == nil {
return errNilPtr
}
*d = nil
return nil
}
}
var sourceValue reflect.Value
switch d := destInterface.(type) {
case *string:
sourceValue = reflect.ValueOf(src)
switch sourceValue.Kind() {
case reflect.Bool,
reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64,
reflect.Float32, reflect.Float64:
*d = asString(src)
return nil
}
case *[]byte:
sourceValue = reflect.ValueOf(src)
if b, ok := asBytes(nil, sourceValue); ok {
*d = b
return nil
}
case *bool:
bv, err := driver.Bool.ConvertValue(src)
if err == nil {
*d = bv.(bool)
}
return err
case *interface{}:
*d = src
return nil
}
if !sourceValue.IsValid() {
sourceValue = reflect.ValueOf(src)
}
if sourceValue.IsValid() && sourceValue.Type().AssignableTo(destValue.Type()) {
switch b := src.(type) {
case []byte:
destValue.Set(reflect.ValueOf(cloneBytes(b)))
default:
destValue.Set(sourceValue)
}
return nil
}
if destValue.Kind() == sourceValue.Kind() && sourceValue.Type().ConvertibleTo(destValue.Type()) {
destValue.Set(sourceValue.Convert(destValue.Type()))
return nil
}
switch destValue.Kind() {
case reflect.Ptr:
if src == nil {
destValue.Set(reflect.Zero(destValue.Type()))
return nil
}
destValue.Set(reflect.New(destValue.Type().Elem()))
return CopyInterface(destValue, src)
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
s := asString(src)
i64, err := strconv.ParseInt(s, 10, destValue.Type().Bits())
if err != nil {
err = strconvErr(err)
return fmt.Errorf("converting driver.Value type %T (%q) to a %s: %v", src, s, destValue.Kind(), err)
}
destValue.SetInt(i64)
return nil
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
s := asString(src)
u64, err := strconv.ParseUint(s, 10, destValue.Type().Bits())
if err != nil {
err = strconvErr(err)
return fmt.Errorf("converting driver.Value type %T (%q) to a %s: %v", src, s, destValue.Kind(), err)
}
destValue.SetUint(u64)
return nil
case reflect.Float32, reflect.Float64:
s := asString(src)
f64, err := strconv.ParseFloat(s, destValue.Type().Bits())
if err != nil {
err = strconvErr(err)
return fmt.Errorf("converting driver.Value type %T (%q) to a %s: %v", src, s, destValue.Kind(), err)
}
destValue.SetFloat(f64)
return nil
}
return fmt.Errorf("unsupported Scan, storing driver.Value type %T into type %T", src, destInterface)
}
// The following routines were also taken from the sql package to support CopyInterface
// which of course was private..
func strconvErr(err error) error {
if ne, ok := err.(*strconv.NumError); ok {
return ne.Err
}
return err
}
func cloneBytes(b []byte) []byte {
if b == nil {
return nil
}
c := make([]byte, len(b))
copy(c, b)
return c
}
func asString(src interface{}) string {
switch v := src.(type) {
case string:
return v
case []byte:
return string(v)
}
rv := reflect.ValueOf(src)
switch rv.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return strconv.FormatInt(rv.Int(), 10)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return strconv.FormatUint(rv.Uint(), 10)
case reflect.Float64:
return strconv.FormatFloat(rv.Float(), 'g', -1, 64)
case reflect.Float32:
return strconv.FormatFloat(rv.Float(), 'g', -1, 32)
case reflect.Bool:
return strconv.FormatBool(rv.Bool())
}
return fmt.Sprintf("%v", src)
}
func asBytes(buf []byte, rv reflect.Value) (b []byte, ok bool) {
switch rv.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return strconv.AppendInt(buf, rv.Int(), 10), true
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return strconv.AppendUint(buf, rv.Uint(), 10), true
case reflect.Float32:
return strconv.AppendFloat(buf, rv.Float(), 'g', -1, 32), true
case reflect.Float64:
return strconv.AppendFloat(buf, rv.Float(), 'g', -1, 64), true
case reflect.Bool:
return strconv.AppendBool(buf, rv.Bool()), true
case reflect.String:
s := rv.String()
return append(buf, s...), true
}
return
}