pgx icon indicating copy to clipboard operation
pgx copied to clipboard

No Listen/Notify for pgxpool.Pool ?

Open supermuesli opened this issue 5 years ago • 6 comments

The code snippet below was taken from the docs here

_, err := conn.Exec(context.Background(), "listen channelname")
if err != nil {
    return nil
}

if notification, err := conn.WaitForNotification(context.Background()); err != nil {
    // do something with notification
}

My backend is connected to Postgres via pgxpool.Pool for concurrency reasons. Am I supposed open another connection to Postgres via pgx.Connect and call WaitForNotification from there or can this be done with pgxpool.Pool as well?

supermuesli avatar Mar 20 '21 19:03 supermuesli

I would Acquire the connection for listen/notify from pgxpool.Pool and never return it.

jackc avatar Mar 22 '21 13:03 jackc

But pgxpool.Pool.Acquire returns a pgxpool.Conn. which does not implement WaitForNotification. Only pgx.Conn does. Am I missing something?

supermuesli avatar Mar 22 '21 17:03 supermuesli

You can call Conn() on the pgxpool.Conn to get the underlying connection.

jackc avatar Mar 23 '21 12:03 jackc

You are right. So why not implement a func pgxpool.Conn.WaitForNotification that does exactly that? Something like:

func (pc *Conn) WaitForNotification(ctx context.Context) (*pgconn.Notification, error) {
	// Get the underlying connection
	c := pc.Conn()
	
	var n *pgconn.Notification

	// Return already received notification immediately
	if len(c.notifications) > 0 {
		n = c.notifications[0]
		c.notifications = c.notifications[1:]
		return n, nil
	}

	err := c.pgConn.WaitForNotification(ctx)
	if len(c.notifications) > 0 {
		n = c.notifications[0]
		c.notifications = c.notifications[1:]
	}
	return n, err
}

supermuesli avatar Mar 30 '21 00:03 supermuesli

The reason the pool types don't have WaitForNotification is for there to be a notification, the connection first has to listen. That doesn't make sense at the pool level, only on a specific connection. And a listening connection should never be returned to the pool as it could keep listening and it would essentially leak memory by buffering all received notifications.

jackc avatar Apr 03 '21 15:04 jackc

Yea, it seems you're right again. Learned a lot today, love connection pools, love your project.

supermuesli avatar Apr 03 '21 21:04 supermuesli