Skip to content

Commit

Permalink
gocraft#248 fix Panic on nil pointer to driver.Valuer interface
Browse files Browse the repository at this point in the history
  • Loading branch information
Evgeny Pronin authored and Evgeny Pronin committed Sep 27, 2022
1 parent 36b0b6a commit afbb476
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 2 deletions.
22 changes: 20 additions & 2 deletions interpolate.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,20 @@ var (
typeTime = reflect.TypeOf(time.Time{})
)

func isInterfaceInvalidOrNil(value interface{}) bool {
v := reflect.ValueOf(value)
if !v.IsValid() {
return true
}

switch v.Kind() {
case reflect.Chan, reflect.Func, reflect.Map, reflect.Ptr, reflect.UnsafePointer, reflect.Interface, reflect.Slice:
return v.IsNil()
default:
return false
}
}

func (i *interpolator) encodePlaceholder(value interface{}, topLevel bool) error {
if builder, ok := value.(Builder); ok {
pbuf := NewBuffer()
Expand All @@ -120,9 +134,13 @@ func (i *interpolator) encodePlaceholder(value interface{}, topLevel bool) error
}

if valuer, ok := value.(driver.Valuer); ok {
// get driver.Valuer's data
var err error
value, err = valuer.Value()
if isInterfaceInvalidOrNil(valuer) {
value = nil
} else {
// get driver.Valuer's data
value, err = valuer.Value()
}
if err != nil {
return err
}
Expand Down
14 changes: 14 additions & 0 deletions interpolate_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package dbr

import (
"database/sql/driver"
"strings"
"testing"
"time"
Expand All @@ -9,6 +10,13 @@ import (
"github.com/stretchr/testify/require"
)

type TestValuer struct {
}

func (m TestValuer) Value() (driver.Value, error) {
return nil, nil
}

func TestInterpolateIgnoreBinary(t *testing.T) {
for _, test := range []struct {
query string
Expand All @@ -22,6 +30,12 @@ func TestInterpolateIgnoreBinary(t *testing.T) {
wantQuery: "1",
wantValue: nil,
},
{
query: "?",
value: []interface{}{(*TestValuer)(nil)},
wantQuery: "NULL",
wantValue: nil,
},
{
query: "?",
value: []interface{}{[]byte{1, 2, 3}},
Expand Down

0 comments on commit afbb476

Please sign in to comment.