diff --git a/CHANGELOG.md b/CHANGELOG.md index 92caabb..0fe9ff2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,9 +5,11 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). -## [1.4.5] - 2014-04-19 +## [1.4.5] - 2014-04-20 ### Changed - used int64 instead of int in `Queryer.Count` (#37) +- fixed timer performance issue (#38) +- fixed StmtMaxIdleTime missing issue (#38) ## [1.4.4] - 2014-04-19 ### Added diff --git a/context_stmt.go b/context_stmt.go index a390e6e..3c94352 100644 --- a/context_stmt.go +++ b/context_stmt.go @@ -65,8 +65,11 @@ func (db *Context) closeStaleStmt() { } func (db *Context) checkIdleStmt() { + delay := time.NewTicker(db.stmtMaxIdleTime) + defer delay.Stop() + for { - <-time.After(db.stmtMaxIdleTime) + <-delay.C db.closeStaleStmt() } diff --git a/context_stmt_test.go b/context_stmt_test.go index 176e992..4c51e6c 100644 --- a/context_stmt_test.go +++ b/context_stmt_test.go @@ -28,9 +28,11 @@ func TestStmt(t *testing.T) { _, err = d.Exec("INSERT INTO `rows`(`id`) VALUES(4)") require.NoError(t, err) - db := Open(d) + stmtMaxIdleTime := StmtMaxIdleTime - db.stmtMaxIdleTime = 1 * time.Second + StmtMaxIdleTime = 1 * time.Second + db := Open(d) + StmtMaxIdleTime = stmtMaxIdleTime tests := []struct { name string @@ -123,7 +125,9 @@ func TestStmt(t *testing.T) { require.NoError(t, err) require.Equal(t, int64(1), affected) + db.stmtsMutex.Lock() s, ok := db.stmts[q] + db.stmtsMutex.Unlock() require.True(t, ok) require.False(t, s.isUsing) diff --git a/db.go b/db.go index d7d5b84..13d8208 100644 --- a/db.go +++ b/db.go @@ -27,25 +27,22 @@ type DB struct { // Open creates a new DB instance with the provided database connections. func Open(dbs ...*sql.DB) *DB { d := &DB{ - Context: &Context{ - DB: dbs[0], - stmts: make(map[string]*Stmt), - Index: 0, - stmtMaxIdleTime: StmtMaxIdleTime, - }, dhts: make(map[string]*shardid.DHT), } for i, db := range dbs { ctx := &Context{ - DB: db, - Index: i, - stmts: make(map[string]*Stmt), + DB: db, + Index: i, + stmts: make(map[string]*Stmt), + stmtMaxIdleTime: StmtMaxIdleTime, } d.dbs = append(d.dbs, ctx) go ctx.checkIdleStmt() } + d.Context = d.dbs[0] + return d } @@ -58,9 +55,10 @@ func (db *DB) Add(dbs ...*sql.DB) { for i, d := range dbs { ctx := &Context{ - DB: d, - Index: n + i, - stmts: make(map[string]*Stmt), + DB: d, + Index: n + i, + stmts: make(map[string]*Stmt), + stmtMaxIdleTime: StmtMaxIdleTime, } db.dbs = append(db.dbs, ctx) go ctx.checkIdleStmt()