Skip to content

Commit

Permalink
Add Hijack from v5
Browse files Browse the repository at this point in the history
  • Loading branch information
jackc committed Jun 3, 2022
1 parent dc0ad04 commit 37c3f15
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
16 changes: 16 additions & 0 deletions pgxpool/conn.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,22 @@ func (c *Conn) Release() {
}()
}

// Hijack assumes ownership of the connection from the pool. Caller is responsible for closing the connection. Hijack
// will panic if called on an already released or hijacked connection.
func (c *Conn) Hijack() *pgx.Conn {
if c.res == nil {
panic("cannot hijack already released or hijacked connection")
}

conn := c.Conn()
res := c.res
c.res = nil

res.Hijack()

return conn
}

func (c *Conn) Exec(ctx context.Context, sql string, arguments ...interface{}) (pgconn.CommandTag, error) {
return c.Conn().Exec(ctx, sql, arguments...)
}
Expand Down
26 changes: 26 additions & 0 deletions pgxpool/pool_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,32 @@ func TestPoolAcquireAndConnRelease(t *testing.T) {
c.Release()
}

func TestPoolAcquireAndConnHijack(t *testing.T) {
t.Parallel()

ctx := context.Background()

pool, err := pgxpool.Connect(ctx, os.Getenv("PGX_TEST_DATABASE"))
require.NoError(t, err)
defer pool.Close()

c, err := pool.Acquire(ctx)
require.NoError(t, err)

connsBeforeHijack := pool.Stat().TotalConns()

conn := c.Hijack()
defer conn.Close(ctx)

connsAfterHijack := pool.Stat().TotalConns()
require.Equal(t, connsBeforeHijack-1, connsAfterHijack)

var n int32
err = conn.QueryRow(ctx, `select 1`).Scan(&n)
require.NoError(t, err)
require.Equal(t, int32(1), n)
}

func TestPoolAcquireFunc(t *testing.T) {
t.Parallel()

Expand Down

0 comments on commit 37c3f15

Please sign in to comment.