Skip to content

Commit 110be07

Browse files
committed
make sure Close always removes the runtime finalizer
This commit fixes a bug in {SQLiteConn,SQLiteStmt}.Close that would lead to the runtime finalizer not being removed if there was an error closing the connection or statement. This commit also makes it safe to call SQLiteConn.Close multiple times.
1 parent ab13d63 commit 110be07

File tree

1 file changed

+15
-22
lines changed

1 file changed

+15
-22
lines changed

sqlite3.go

+15-22
Original file line numberDiff line numberDiff line change
@@ -1782,26 +1782,20 @@ func (d *SQLiteDriver) Open(dsn string) (driver.Conn, error) {
17821782
}
17831783

17841784
// Close the connection.
1785-
func (c *SQLiteConn) Close() error {
1785+
func (c *SQLiteConn) Close() (err error) {
1786+
c.mu.Lock()
1787+
defer c.mu.Unlock()
1788+
if c.db == nil {
1789+
return nil // Already closed
1790+
}
1791+
runtime.SetFinalizer(c, nil)
17861792
rv := C.sqlite3_close_v2(c.db)
17871793
if rv != C.SQLITE_OK {
1788-
return c.lastError()
1794+
err = c.lastError()
17891795
}
17901796
deleteHandles(c)
1791-
c.mu.Lock()
17921797
c.db = nil
1793-
c.mu.Unlock()
1794-
runtime.SetFinalizer(c, nil)
1795-
return nil
1796-
}
1797-
1798-
func (c *SQLiteConn) dbConnOpen() bool {
1799-
if c == nil {
1800-
return false
1801-
}
1802-
c.mu.Lock()
1803-
defer c.mu.Unlock()
1804-
return c.db != nil
1798+
return err
18051799
}
18061800

18071801
// Prepare the query string. Return a new statement.
@@ -1901,16 +1895,15 @@ func (s *SQLiteStmt) Close() error {
19011895
return nil
19021896
}
19031897
s.closed = true
1904-
if !s.c.dbConnOpen() {
1905-
return errors.New("sqlite statement with already closed database connection")
1906-
}
1907-
rv := C.sqlite3_finalize(s.s)
1898+
conn := s.c
1899+
stmt := s.s
1900+
s.c = nil
19081901
s.s = nil
1902+
runtime.SetFinalizer(s, nil)
1903+
rv := C.sqlite3_finalize(stmt)
19091904
if rv != C.SQLITE_OK {
1910-
return s.c.lastError()
1905+
return conn.lastError()
19111906
}
1912-
s.c = nil
1913-
runtime.SetFinalizer(s, nil)
19141907
return nil
19151908
}
19161909

0 commit comments

Comments
 (0)