From b3511bfdd742af558b54eb6160aca9446d762a19 Mon Sep 17 00:00:00 2001 From: Collin Van Dyck Date: Tue, 17 Jul 2018 20:29:43 -0400 Subject: [PATCH] Ensure that SqliteStmt.closed property is guarded. Because the closed property of the SQLiteRows's *SqliteStmt was not guarded, it was causing an issue during context cancellation. https://github.com/segmentio/go-sqlite3/blob/be424d27acde822f080bdcd8a7ae6abd4d7d801e/sqlite3.go#L1785-L1796 When a statement is performing a query(), if it determines that the context has been canceled, it will launch a goroutine that closes the resulting driver.Rows if it's not already completed. If the driver.Rows is not done (and the context has been canceled), it will interrupt the connection and more importantly, perform a rows.Close(). The method rows.Close() guards the closed bool with a sync.Mutex to set it to true. If a reader is reading from the SqliteRow, it will call Next() and that performs this check: https://github.com/segmentio/go-sqlite3/blob/be424d27acde822f080bdcd8a7ae6abd4d7d801e/sqlite3.go#L1915-L1917 Because this is not guarded, a data race ensues, and this was actually caught by the Go race detector recently. I didn't include a test case here because the fix seemed straightforward enough and because race conditions are hard to test for. It's been verified in another program that this fixes the issue. If tests should be provided I'm more than happy to do so. --- sqlite3.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sqlite3.go b/sqlite3.go index d8fe4b0..b97647b 100644 --- a/sqlite3.go +++ b/sqlite3.go @@ -1883,11 +1883,11 @@ func (rc *SQLiteRows) DeclTypes() []string { // Next move cursor to next. func (rc *SQLiteRows) Next(dest []driver.Value) error { + rc.s.mu.Lock() + defer rc.s.mu.Unlock() if rc.s.closed { return io.EOF } - rc.s.mu.Lock() - defer rc.s.mu.Unlock() rv := C.sqlite3_step(rc.s.s) if rv == C.SQLITE_DONE { return io.EOF