Skip to content

Commit 69048c2

Browse files
author
José Carlos
authored
Merge pull request #275 from upper/issue-270
Don't use statements that are marked as dead
2 parents bafbd90 + 416e860 commit 69048c2

File tree

2 files changed

+14
-7
lines changed

2 files changed

+14
-7
lines changed

internal/sqladapter/database.go

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -359,8 +359,10 @@ func (d *database) prepareStatement(stmt *exql.Statement) (*Stmt, string, error)
359359
pc, ok := d.cachedStatements.ReadRaw(stmt)
360360
if ok {
361361
// The statement was cached.
362-
ps := pc.(*Stmt).Open()
363-
return ps, ps.query, nil
362+
ps, err := pc.(*Stmt).Open()
363+
if err == nil {
364+
return ps, ps.query, nil
365+
}
364366
}
365367

366368
// Plain SQL query.

internal/sqladapter/statement.go

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package sqladapter
22

33
import (
44
"database/sql"
5+
"errors"
56
"sync/atomic"
67
)
78

@@ -39,19 +40,23 @@ func NewStatement(stmt *sql.Stmt, query string) *Stmt {
3940
}
4041

4142
// Open marks the statement as in-use
42-
func (c *Stmt) Open() *Stmt {
43+
func (c *Stmt) Open() (*Stmt, error) {
44+
if atomic.LoadInt32(&c.dead) > 0 {
45+
return nil, errors.New("statement is dead")
46+
}
4347
atomic.AddInt64(&c.count, 1)
44-
return c
48+
return c, nil
4549
}
4650

4751
// Close closes the underlying statement if no other go-routine is using it.
4852
func (c *Stmt) Close() {
4953
if atomic.AddInt64(&c.count, -1) > 0 {
50-
// There are another goroutines using this statement so we don't want to
51-
// close it for real.
54+
// If this counter is more than 0 then there are other goroutines using
55+
// this statement so we don't want to close it for real.
5256
return
5357
}
54-
if atomic.LoadInt32(&c.dead) > 0 {
58+
59+
if atomic.LoadInt32(&c.dead) > 0 && atomic.LoadInt64(&c.count) <= 0 {
5560
// Statement is dead and we can close it for real.
5661
c.Stmt.Close()
5762
// Reduce active statements counter.

0 commit comments

Comments
 (0)