Add Hijack from v5

pull/1213/head
Jack Christensen 2022-04-14 11:50:12 -05:00 committed by Jack Christensen
parent dc0ad04ff5
commit 37c3f157bc
2 changed files with 42 additions and 0 deletions

View File

@ -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...)
}

View File

@ -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()