No Listen/Notify for pgxpool.Pool ?
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?
I would Acquire the connection for listen/notify from pgxpool.Pool and never return it.
But pgxpool.Pool.Acquire returns a pgxpool.Conn. which does not implement WaitForNotification. Only pgx.Conn does. Am I missing something?
You can call Conn() on the pgxpool.Conn to get the underlying connection.
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
}
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.
Yea, it seems you're right again. Learned a lot today, love connection pools, love your project.