@@ -4,6 +4,7 @@ package pq
4
4
// This module contains support for Postgres LISTEN/NOTIFY.
5
5
6
6
import (
7
+ "context"
7
8
"database/sql/driver"
8
9
"errors"
9
10
"fmt"
@@ -40,6 +41,51 @@ func SetNotificationHandler(c driver.Conn, handler func(*Notification)) {
40
41
c .(* conn ).notificationHandler = handler
41
42
}
42
43
44
+ // NotificationHandlerConnector wraps a regular connector and sets a notification handler
45
+ // on it.
46
+ type NotificationHandlerConnector struct {
47
+ driver.Connector
48
+ notificationHandler func (* Notification )
49
+ }
50
+
51
+ // Connect calls the underlying connector's connect method and then sets the
52
+ // notification handler.
53
+ func (n * NotificationHandlerConnector ) Connect (ctx context.Context ) (driver.Conn , error ) {
54
+ c , err := n .Connector .Connect (ctx )
55
+ if err == nil {
56
+ SetNotificationHandler (c , n .notificationHandler )
57
+ }
58
+ return c , err
59
+ }
60
+
61
+ // ConnectorNotificationHandler returns the currently set notification handler, if any. If
62
+ // the given connector is not a result of ConnectorWithNotificationHandler, nil is
63
+ // returned.
64
+ func ConnectorNotificationHandler (c driver.Connector ) func (* Notification ) {
65
+ if c , ok := c .(* NotificationHandlerConnector ); ok {
66
+ return c .notificationHandler
67
+ }
68
+ return nil
69
+ }
70
+
71
+ // ConnectorWithNotificationHandler creates or sets the given handler for the given
72
+ // connector. If the given connector is a result of calling this function
73
+ // previously, it is simply set on the given connector and returned. Otherwise,
74
+ // this returns a new connector wrapping the given one and setting the notification
75
+ // handler. A nil notification handler may be used to unset it.
76
+ //
77
+ // The returned connector is intended to be used with database/sql.OpenDB.
78
+ //
79
+ // Note: Notification handlers are executed synchronously by pq meaning commands
80
+ // won't continue to be processed until the handler returns.
81
+ func ConnectorWithNotificationHandler (c driver.Connector , handler func (* Notification )) * NotificationHandlerConnector {
82
+ if c , ok := c .(* NotificationHandlerConnector ); ok {
83
+ c .notificationHandler = handler
84
+ return c
85
+ }
86
+ return & NotificationHandlerConnector {Connector : c , notificationHandler : handler }
87
+ }
88
+
43
89
const (
44
90
connStateIdle int32 = iota
45
91
connStateExpectResponse
0 commit comments