Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support new custom Validation Proxy function, defaulting to existing sql.driver.Valuer transform. #155 #156

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 26 additions & 9 deletions util.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,27 @@ import (
"time"
)

// Interface for transforming values to validation proxies.
//
// The input is the value to transform and the output is
// the new value and a boolean whether the value was
// actually transformed.
type ValidationValuer func(interface{}) (interface{}, bool)

// Default tranformation function to convert sql.driver.Valuer
// based values
func sqlValueValuer(orig interface{}) (interface{}, bool) {
if valuer, ok := orig.(driver.Valuer); ok {
if value, err := valuer.Value(); err == nil {
return value, true
}
}
return orig, false
}

var (
bytesType = reflect.TypeOf([]byte(nil))
valuerType = reflect.TypeOf((*driver.Valuer)(nil)).Elem()
bytesType = reflect.TypeOf([]byte(nil))
getValidationProxy = sqlValueValuer
)

// EnsureString ensures the given value is a string.
Expand Down Expand Up @@ -148,16 +166,15 @@ func Indirect(value interface{}) (interface{}, bool) {
}
}

if rv.Type().Implements(valuerType) {
return indirectValuer(value.(driver.Valuer))
if getValidationProxy != nil {
if val, ok := getValidationProxy(value); ok {
return Indirect(val)
}
}

return value, false
}

func indirectValuer(valuer driver.Valuer) (interface{}, bool) {
if value, err := valuer.Value(); value != nil && err == nil {
return Indirect(value)
}
return nil, true
func SetValidationValuer(valuer ValidationValuer) {
getValidationProxy = valuer
}