feat(Type): add driver.Valuer implementation to Optional type
This commit is contained in:
@@ -2,6 +2,7 @@ package Type
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"database/sql/driver"
|
||||
"encoding/json"
|
||||
)
|
||||
|
||||
@@ -50,6 +51,8 @@ var (
|
||||
_ ValueContainer = (*Result[any])(nil)
|
||||
_ sql.Scanner = (*Optional[any])(nil)
|
||||
_ sql.Scanner = (*Result[any])(nil)
|
||||
_ driver.Valuer = (*Optional[any])(nil)
|
||||
// _ driver.Valuer = (*Result[any])(nil)
|
||||
_ json.Marshaler = (*Optional[any])(nil)
|
||||
// _ json.Marshaler = (*Result[any])(nil)
|
||||
_ json.Unmarshaler = (*Optional[any])(nil)
|
||||
|
||||
@@ -2,7 +2,9 @@ package Type
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"database/sql/driver"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"time"
|
||||
@@ -285,3 +287,34 @@ func (opt *Optional[T]) UnmarshalJSON(data []byte) error {
|
||||
opt.present = true
|
||||
return nil
|
||||
}
|
||||
|
||||
func (o Optional[T]) Value() (driver.Value, error) {
|
||||
if !o.present {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
switch v := any(o.Value).(type) {
|
||||
|
||||
case string, bool,
|
||||
int, int8, int16, int32, int64,
|
||||
uint, uint8, uint16, uint32, uint64, uintptr,
|
||||
float32, float64,
|
||||
complex64, complex128:
|
||||
return v, nil
|
||||
|
||||
case *string, *bool,
|
||||
*int, *int8, *int16, *int32, *int64,
|
||||
*uint, *uint8, *uint16, *uint32, *uint64, *uintptr,
|
||||
*float32, *float64,
|
||||
*complex64, *complex128:
|
||||
return v, nil
|
||||
|
||||
case fmt.Stringer:
|
||||
return v.String(), nil
|
||||
case driver.Valuer:
|
||||
return v.Value()
|
||||
|
||||
default:
|
||||
return nil, errors.New("unsupported type for Optional")
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user