Skip to content

Commit

Permalink
statement: Fix conversion of Valuer (#710)
Browse files Browse the repository at this point in the history
Updates #709 
Fixes #706
  • Loading branch information
linxGnu authored and julienschmidt committed Nov 17, 2017
1 parent b816f3d commit 370fec2
Show file tree
Hide file tree
Showing 4 changed files with 57 additions and 5 deletions.
1 change: 1 addition & 0 deletions AUTHORS
Expand Up @@ -46,6 +46,7 @@ Kamil Dziedzic <kamil at klecza.pl>
Kevin Malachowski <kevin at chowski.com>
Lennart Rudolph <lrudolph at hmc.edu>
Leonardo YongUk Kim <dalinaum at gmail.com>
Linh Tran Tuan <linhduonggnu at gmail.com>
Lion Yang <lion at aosc.xyz>
Luca Looz <luca.looz92 at gmail.com>
Lucas Liu <extrafliu at gmail.com>
Expand Down
6 changes: 1 addition & 5 deletions connection_go18.go
Expand Up @@ -197,10 +197,6 @@ func (mc *mysqlConn) startWatcher() {
}

func (mc *mysqlConn) CheckNamedValue(nv *driver.NamedValue) (err error) {
value, err := converter{}.ConvertValue(nv.Value)
if err != nil {
return driver.ErrSkip
}
nv.Value = value
nv.Value, err = converter{}.ConvertValue(nv.Value)
return
}
49 changes: 49 additions & 0 deletions driver_test.go
Expand Up @@ -529,6 +529,55 @@ func TestValuer(t *testing.T) {
})
}

type testValuerWithValidation struct {
value string
}

func (tv testValuerWithValidation) Value() (driver.Value, error) {
if len(tv.value) == 0 {
return nil, fmt.Errorf("Invalid string valuer. Value must not be empty")
}

return tv.value, nil
}

func TestValuerWithValidation(t *testing.T) {
runTests(t, dsn, func(dbt *DBTest) {
in := testValuerWithValidation{"a_value"}
var out string
var rows *sql.Rows

dbt.mustExec("CREATE TABLE testValuer (value VARCHAR(255)) CHARACTER SET utf8")
dbt.mustExec("INSERT INTO testValuer VALUES (?)", in)

rows = dbt.mustQuery("SELECT value FROM testValuer")
defer rows.Close()

if rows.Next() {
rows.Scan(&out)
if in.value != out {
dbt.Errorf("Valuer: %v != %s", in, out)
}
} else {
dbt.Errorf("Valuer: no data")
}

if _, err := dbt.db.Exec("INSERT INTO testValuer VALUES (?)", testValuerWithValidation{""}); err == nil {
dbt.Errorf("Failed to check valuer error")
}

if _, err := dbt.db.Exec("INSERT INTO testValuer VALUES (?)", nil); err != nil {
dbt.Errorf("Failed to check nil")
}

if _, err := dbt.db.Exec("INSERT INTO testValuer VALUES (?)", map[string]bool{}); err == nil {
dbt.Errorf("Failed to check not valuer")
}

dbt.mustExec("DROP TABLE IF EXISTS testValuer")
})
}

type timeTests struct {
dbtype string
tlayout string
Expand Down
6 changes: 6 additions & 0 deletions statement.go
Expand Up @@ -137,6 +137,12 @@ func (c converter) ConvertValue(v interface{}) (driver.Value, error) {
return v, nil
}

if v != nil {
if valuer, ok := v.(driver.Valuer); ok {
return valuer.Value()
}
}

rv := reflect.ValueOf(v)
switch rv.Kind() {
case reflect.Ptr:
Expand Down

0 comments on commit 370fec2

Please sign in to comment.