Skip to content

Commit 6d0b39d

Browse files
authored
Merge pull request #583 from lucasmrod/bug/#542-nil-byte-slice-to-null-blob
Add nil check in bind and a test
2 parents 5a7d2e2 + 140b805 commit 6d0b39d

File tree

2 files changed

+27
-4
lines changed

2 files changed

+27
-4
lines changed

sqlite3.go

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1511,11 +1511,15 @@ func (s *SQLiteStmt) bind(args []namedValue) error {
15111511
case float64:
15121512
rv = C.sqlite3_bind_double(s.s, n, C.double(v))
15131513
case []byte:
1514-
ln := len(v)
1515-
if ln == 0 {
1516-
v = placeHolder
1514+
if v == nil {
1515+
rv = C.sqlite3_bind_null(s.s, n)
1516+
} else {
1517+
ln := len(v)
1518+
if ln == 0 {
1519+
v = placeHolder
1520+
}
1521+
rv = C._sqlite3_bind_blob(s.s, n, unsafe.Pointer(&v[0]), C.int(ln))
15171522
}
1518-
rv = C._sqlite3_bind_blob(s.s, n, unsafe.Pointer(&v[0]), C.int(ln))
15191523
case time.Time:
15201524
b := []byte(v.Format(SQLiteTimestampFormats[0]))
15211525
rv = C._sqlite3_bind_text(s.s, n, (*C.char)(unsafe.Pointer(&b[0])), C.int(len(b)))

sqlite3_test.go

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1580,6 +1580,25 @@ func TestNilAndEmptyBytes(t *testing.T) {
15801580
}
15811581
}
15821582

1583+
func TestInsertNilByteSlice(t *testing.T) {
1584+
db, err := sql.Open("sqlite3", ":memory:")
1585+
if err != nil {
1586+
t.Fatal(err)
1587+
}
1588+
defer db.Close()
1589+
if _, err := db.Exec("create table blob_not_null (b blob not null)"); err != nil {
1590+
t.Fatal(err)
1591+
}
1592+
var nilSlice []byte
1593+
if _, err := db.Exec("insert into blob_not_null (b) values (?)", nilSlice); err == nil {
1594+
t.Fatal("didn't expect INSERT to 'not null' column with a nil []byte slice to work")
1595+
}
1596+
zeroLenSlice := []byte{}
1597+
if _, err := db.Exec("insert into blob_not_null (b) values (?)", zeroLenSlice); err != nil {
1598+
t.Fatal("failed to insert zero-length slice")
1599+
}
1600+
}
1601+
15831602
var customFunctionOnce sync.Once
15841603

15851604
func BenchmarkCustomFunctions(b *testing.B) {

0 commit comments

Comments
 (0)