Skip to content

Commit a819994

Browse files
authored
Merge pull request #427 from otoolep/conn_stmt_race
Address data race during close database and statement
2 parents 83c59d8 + cd1cbf5 commit a819994

File tree

1 file changed

+14
-1
lines changed

1 file changed

+14
-1
lines changed

sqlite3.go

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,7 @@ import (
113113
"runtime"
114114
"strconv"
115115
"strings"
116+
"sync"
116117
"time"
117118
"unsafe"
118119

@@ -157,6 +158,7 @@ type SQLiteDriver struct {
157158

158159
// SQLiteConn implement sql.Conn.
159160
type SQLiteConn struct {
161+
dbMu sync.Mutex
160162
db *C.sqlite3
161163
loc *time.Location
162164
txlock string
@@ -679,11 +681,22 @@ func (c *SQLiteConn) Close() error {
679681
return c.lastError()
680682
}
681683
deleteHandles(c)
684+
c.dbMu.Lock()
682685
c.db = nil
686+
c.dbMu.Unlock()
683687
runtime.SetFinalizer(c, nil)
684688
return nil
685689
}
686690

691+
func (c *SQLiteConn) dbConnOpen() bool {
692+
if c == nil {
693+
return false
694+
}
695+
c.dbMu.Lock()
696+
defer c.dbMu.Unlock()
697+
return c.db != nil
698+
}
699+
687700
// Prepare the query string. Return a new statement.
688701
func (c *SQLiteConn) Prepare(query string) (driver.Stmt, error) {
689702
return c.prepare(context.Background(), query)
@@ -713,7 +726,7 @@ func (s *SQLiteStmt) Close() error {
713726
return nil
714727
}
715728
s.closed = true
716-
if s.c == nil || s.c.db == nil {
729+
if !s.c.dbConnOpen() {
717730
return errors.New("sqlite statement with already closed database connection")
718731
}
719732
rv := C.sqlite3_finalize(s.s)

0 commit comments

Comments
 (0)