Merge pull request #583 from lucasmrod/bug/#542-nil-byte-slice-to-null-blob

Add nil check in bind and a test
This commit is contained in:
mattn 2018-05-31 22:29:18 +09:00 committed by GitHub
commit 6d0b39d7bc
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 27 additions and 4 deletions

View File

@ -1511,11 +1511,15 @@ func (s *SQLiteStmt) bind(args []namedValue) error {
case float64: case float64:
rv = C.sqlite3_bind_double(s.s, n, C.double(v)) rv = C.sqlite3_bind_double(s.s, n, C.double(v))
case []byte: case []byte:
if v == nil {
rv = C.sqlite3_bind_null(s.s, n)
} else {
ln := len(v) ln := len(v)
if ln == 0 { if ln == 0 {
v = placeHolder v = placeHolder
} }
rv = C._sqlite3_bind_blob(s.s, n, unsafe.Pointer(&v[0]), C.int(ln)) rv = C._sqlite3_bind_blob(s.s, n, unsafe.Pointer(&v[0]), C.int(ln))
}
case time.Time: case time.Time:
b := []byte(v.Format(SQLiteTimestampFormats[0])) b := []byte(v.Format(SQLiteTimestampFormats[0]))
rv = C._sqlite3_bind_text(s.s, n, (*C.char)(unsafe.Pointer(&b[0])), C.int(len(b))) rv = C._sqlite3_bind_text(s.s, n, (*C.char)(unsafe.Pointer(&b[0])), C.int(len(b)))

View File

@ -1580,6 +1580,25 @@ func TestNilAndEmptyBytes(t *testing.T) {
} }
} }
func TestInsertNilByteSlice(t *testing.T) {
db, err := sql.Open("sqlite3", ":memory:")
if err != nil {
t.Fatal(err)
}
defer db.Close()
if _, err := db.Exec("create table blob_not_null (b blob not null)"); err != nil {
t.Fatal(err)
}
var nilSlice []byte
if _, err := db.Exec("insert into blob_not_null (b) values (?)", nilSlice); err == nil {
t.Fatal("didn't expect INSERT to 'not null' column with a nil []byte slice to work")
}
zeroLenSlice := []byte{}
if _, err := db.Exec("insert into blob_not_null (b) values (?)", zeroLenSlice); err != nil {
t.Fatal("failed to insert zero-length slice")
}
}
var customFunctionOnce sync.Once var customFunctionOnce sync.Once
func BenchmarkCustomFunctions(b *testing.B) { func BenchmarkCustomFunctions(b *testing.B) {