-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsql.go
69 lines (61 loc) · 1.59 KB
/
sql.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
package goption
import (
"database/sql"
"database/sql/driver"
"fmt"
"reflect"
)
// Scan assigns a value from a database driver.
//
// The src value will be of one of the following types:
//
// int64
// float64
// bool
// []byte
// string
// time.Time
// nil - for NULL values
//
// An error should be returned if the value cannot be stored
// without loss of information.
//
// Reference types such as []byte are only valid until the next call to Scan
// and should not be retained. Their underlying memory is owned by the driver.
// If retention is necessary, copy their values before the next call to Scan.
func (c *Optional[T]) Scan(src any) error {
srcValue, isSrcValid := isValidData(src)
c.isValidValue = isSrcValid
if !isSrcValid {
return nil
}
destType := reflect.TypeOf(c.value)
if srcValue.Type().ConvertibleTo(destType) {
c.value = srcValue.Convert(destType).Interface().(T)
return nil
}
destTypeP := reflect.TypeOf(&c.value)
scannerType := reflect.TypeOf((*sql.Scanner)(nil))
if destTypeP.Implements(scannerType.Elem()) {
var s T
if asScanner, ok := interface{}(&s).(sql.Scanner); ok {
if err := asScanner.Scan(src); err != nil {
return err
}
c.value = s
return nil
}
}
return fmt.Errorf("interface conversion: interface {} is %s, not %s nor implements sql.Scanner", srcValue.Type(), destType)
}
// Value returns a driver Value.
// Value must not panic.
func (c Optional[T]) Value() (driver.Value, error) {
if !c.isValidValue {
return nil, nil
}
if asValuer, ok := interface{}(&c.value).(driver.Valuer); ok {
return asValuer.Value()
}
return c.value, nil
}