mirror of
https://github.com/jackc/pgx.git
synced 2025-05-31 03:32:13 +00:00
Add Hijack to pgxpool.Conn
This commit is contained in:
parent
1ef2cee36e
commit
b03b1666a6
@ -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 ...any) (pgconn.CommandTag, error) {
|
||||
return c.Conn().Exec(ctx, sql, arguments...)
|
||||
}
|
||||
|
@ -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()
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user