• Brad Fitzpatrick's avatar
    database/sql: accept nil pointers to Valuers implemented on value receivers · 0ce1d79a
    Brad Fitzpatrick authored
    The driver.Valuer interface lets types map their Go representation to
    a suitable database/sql/driver.Value.
    
    If a user defines the Value method with a value receiver, such as:
    
        type MyStr string
    
        func (s MyStr) Value() (driver.Value, error) {
            return strings.ToUpper(string(s)), nil
        }
    
    Then they can't use (*MyStr)(nil) as an argument to an SQL call via
    database/sql, because *MyStr also implements driver.Value, but via a
    compiler-generated wrapper which checks whether the pointer is nil and
    panics if so.
    
    We now accept (*MyStr)(nil) and map it to "nil" (an SQL "NULL")
    if the Valuer method is implemented on MyStr instead of *MyStr.
    
    If a user implements the driver.Value interface with a pointer
    receiver, they retain full control of what nil means:
    
        type MyStr string
    
        func (s *MyStr) Value() (driver.Value, error) {
            if s == nil {
                return "missing MyStr", nil
            }
            return strings.ToUpper(string(*s)), nil
        }
    
    Adds tests for both cases.
    
    Fixes #8415
    
    Change-Id: I897d609d80d46e2354d2669a8a3e090688eee3ad
    Reviewed-on: https://go-review.googlesource.com/31259
    Run-TryBot: Brad Fitzpatrick <bradfitz@golang.org>
    TryBot-Result: Gobot Gobot <gobot@golang.org>
    Reviewed-by: 's avatarDaniel Theophanes <kardianos@gmail.com>
    Reviewed-by: 's avatarBrad Fitzpatrick <bradfitz@golang.org>
    0ce1d79a
convert.go 8.89 KB