Skip to content

Commit

Permalink
Update err for single conn pool when context.Done() return first (#1981)
Browse files Browse the repository at this point in the history
* Update err from ctx if reason is nil

* Add a unit test

* Move pool object to the test itself

* Rename a var from cl to cancel

* Add comment for explaining why ctx.Err() is used
  • Loading branch information
xin-tsla authored Jun 23, 2023
1 parent f7e1c98 commit 4e20be7
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
5 changes: 5 additions & 0 deletions internal/pool/pool_single.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,11 @@ func (p *SingleConnPool) Put(ctx context.Context, cn *Conn) {}
func (p *SingleConnPool) Remove(ctx context.Context, cn *Conn, reason error) {
p.cn = nil
p.stickyErr = reason
// If ctx is cancelled without a reason(error) value,
// then the ctx.Error is used as the reason for why the p.cn is assigned nil.
if reason == nil && ctx != nil {
p.stickyErr = ctx.Err()
}
}

func (p *SingleConnPool) Close() error {
Expand Down
25 changes: 25 additions & 0 deletions internal/pool/pool_single_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package pool_test

import (
"context"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"

"github.com/go-pg/pg/v10/internal/pool"
)

var _ = Describe("SingleConnPool", func() {
It("remove a conn due to context is cancelled", func() {
p := pool.NewSingleConnPool(nil, &pool.Conn{})
ctx, cancel := context.WithCancel(context.TODO())
cn, err := p.Get(nil)
Expect(err).To(BeNil())
Expect(cn).ToNot(BeNil())

cancel()
p.Remove(ctx, cn, nil)
cn, err = p.Get(nil)
Expect(cn).To(BeNil())
Expect(err).ToNot(BeNil())
})
})

0 comments on commit 4e20be7

Please sign in to comment.