-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsql.go
More file actions
55 lines (43 loc) · 923 Bytes
/
sql.go
File metadata and controls
55 lines (43 loc) · 923 Bytes
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
package optional
import (
"database/sql"
"database/sql/driver"
"errors"
"fmt"
)
// Scan implements the Scanner interface.
func (v *Val[T]) Scan(value any) error {
if scanner, ok := any(&v.value).(sql.Scanner); ok {
if err := scanner.Scan(value); err != nil {
v.value, v.hasVal = *new(T), false
return fmt.Errorf("scan value: %w", err)
}
v.hasVal = true
return nil
}
if value == nil {
v.value, v.hasVal = *new(T), false
return nil
}
val, ok := value.(T)
if !ok {
return errors.New("unexpected value type")
}
v.hasVal = true
v.value = val
return nil
}
// Value implements the driver Valuer interface.
func (v Val[T]) Value() (driver.Value, error) {
if !v.hasVal {
return nil, nil
}
if v, ok := any(v.value).(driver.Valuer); ok {
res, err := v.Value()
if err != nil {
return nil, fmt.Errorf("get driver value: %w", err)
}
return res, nil
}
return v.value, nil
}