From 8d6d326be62813261950d3fe807f38a8977596b2 Mon Sep 17 00:00:00 2001 From: Lucas Manuel Rodriguez Date: Wed, 30 May 2018 21:39:01 -0300 Subject: [PATCH 1/2] Add nil check in bind and a test --- sqlite3.go | 12 ++++++++---- sqlite3_test.go | 15 +++++++++++++++ 2 files changed, 23 insertions(+), 4 deletions(-) diff --git a/sqlite3.go b/sqlite3.go index 75a5ee8..f9bbf12 100644 --- a/sqlite3.go +++ b/sqlite3.go @@ -1511,11 +1511,15 @@ func (s *SQLiteStmt) bind(args []namedValue) error { case float64: rv = C.sqlite3_bind_double(s.s, n, C.double(v)) case []byte: - ln := len(v) - if ln == 0 { - v = placeHolder + if v == nil { + rv = C.sqlite3_bind_null(s.s, n) + } else { + ln := len(v) + if ln == 0 { + 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: b := []byte(v.Format(SQLiteTimestampFormats[0])) rv = C._sqlite3_bind_text(s.s, n, (*C.char)(unsafe.Pointer(&b[0])), C.int(len(b))) diff --git a/sqlite3_test.go b/sqlite3_test.go index 782f57c..1013d34 100644 --- a/sqlite3_test.go +++ b/sqlite3_test.go @@ -1580,6 +1580,21 @@ 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") + } +} + var customFunctionOnce sync.Once func BenchmarkCustomFunctions(b *testing.B) { From 140b80506dd0ecc8029baa816ac008eea6309e02 Mon Sep 17 00:00:00 2001 From: Lucas Manuel Rodriguez Date: Thu, 31 May 2018 08:22:26 -0300 Subject: [PATCH 2/2] Add zero-length slice test --- sqlite3_test.go | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/sqlite3_test.go b/sqlite3_test.go index 1013d34..eadcf4a 100644 --- a/sqlite3_test.go +++ b/sqlite3_test.go @@ -1593,6 +1593,10 @@ func TestInsertNilByteSlice(t *testing.T) { 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