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

Handling nil valuers. #260

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
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
12 changes: 7 additions & 5 deletions interpolate.go
Original file line number Diff line number Diff line change
Expand Up @@ -119,20 +119,22 @@ func (i *interpolator) encodePlaceholder(value interface{}, topLevel bool) error
return nil
}

v := reflect.ValueOf(value)
if value == nil || (v.Kind() == reflect.Ptr && v.IsNil()) {
i.WriteString("NULL")
return nil
}

if valuer, ok := value.(driver.Valuer); ok {
// get driver.Valuer's data
var err error
value, err = valuer.Value()
if err != nil {
return err
}
v = reflect.ValueOf(value)
}

if value == nil {
i.WriteString("NULL")
return nil
}
v := reflect.ValueOf(value)
switch v.Kind() {
case reflect.String:
i.WriteString(i.EncodeString(v.String()))
Expand Down
51 changes: 51 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 Down Expand Up @@ -177,6 +178,56 @@ func TestCommonSQLInjections(t *testing.T) {
}
}

// testValuer is a simple implementation of driver.Value, for testing purposes
type testValuer struct{}

func (tv testValuer) Value() (driver.Value, error) {
return "ok", nil
}

// Ensures that nil driver.Valuer values are handler correctly.
func TestEncodePlaceholderHandlesNilValuers(t *testing.T) {
i := interpolator{
Buffer: NewBuffer(),
Dialect: dialect.MySQL,
IgnoreBinary: true,
}

for _, test := range []struct {
name string
value func() interface{}
}{
{
name: "nil value",
value: func() interface{} { return nil },
},
{
name: "nil valuer pointer",
value: func() interface{} {
var v *testValuer
return v
},
},
{
name: "not nil valuer pointer",
value: func() interface{} { return &testValuer{} },
},
{
name: "value",
value: func() interface{} { return 123 },
},
{
name: "valuer",
value: func() interface{} { return testValuer{} },
},
} {
t.Run(test.name, func(t *testing.T) {
err := i.encodePlaceholder(test.value(), true)
require.NoError(t, err)
})
}
}

// InjectionAttempts is a newline separated list of common SQL injection exploits
// taken from https://wfuzz.googlecode.com/svn/trunk/wordlist/Injections/SQL.txt

Expand Down