1 //go:build go1.10 2 // +build go1.10 3 4 package pq 5 6 import ( 7 "context" 8 "database/sql/driver" 9 ) 10 11 // NoticeHandler returns the notice handler on the given connection, if any. A 12 // runtime panic occurs if c is not a pq connection. This is rarely used 13 // directly, use ConnectorNoticeHandler and ConnectorWithNoticeHandler instead. 14 func NoticeHandler(c driver.Conn) func(*Error) { 15 return c.(*conn).noticeHandler 16 } 17 18 // SetNoticeHandler sets the given notice handler on the given connection. A 19 // runtime panic occurs if c is not a pq connection. A nil handler may be used 20 // to unset it. This is rarely used directly, use ConnectorNoticeHandler and 21 // ConnectorWithNoticeHandler instead. 22 // 23 // Note: Notice handlers are executed synchronously by pq meaning commands 24 // won't continue to be processed until the handler returns. 25 func SetNoticeHandler(c driver.Conn, handler func(*Error)) { 26 c.(*conn).noticeHandler = handler 27 } 28 29 // NoticeHandlerConnector wraps a regular connector and sets a notice handler 30 // on it. 31 type NoticeHandlerConnector struct { 32 driver.Connector 33 noticeHandler func(*Error) 34 } 35 36 // Connect calls the underlying connector's connect method and then sets the 37 // notice handler. 38 func (n *NoticeHandlerConnector) Connect(ctx context.Context) (driver.Conn, error) { 39 c, err := n.Connector.Connect(ctx) 40 if err == nil { 41 SetNoticeHandler(c, n.noticeHandler) 42 } 43 return c, err 44 } 45 46 // ConnectorNoticeHandler returns the currently set notice handler, if any. If 47 // the given connector is not a result of ConnectorWithNoticeHandler, nil is 48 // returned. 49 func ConnectorNoticeHandler(c driver.Connector) func(*Error) { 50 if c, ok := c.(*NoticeHandlerConnector); ok { 51 return c.noticeHandler 52 } 53 return nil 54 } 55 56 // ConnectorWithNoticeHandler creates or sets the given handler for the given 57 // connector. If the given connector is a result of calling this function 58 // previously, it is simply set on the given connector and returned. Otherwise, 59 // this returns a new connector wrapping the given one and setting the notice 60 // handler. A nil notice handler may be used to unset it. 61 // 62 // The returned connector is intended to be used with database/sql.OpenDB. 63 // 64 // Note: Notice handlers are executed synchronously by pq meaning commands 65 // won't continue to be processed until the handler returns. 66 func ConnectorWithNoticeHandler(c driver.Connector, handler func(*Error)) *NoticeHandlerConnector { 67 if c, ok := c.(*NoticeHandlerConnector); ok { 68 c.noticeHandler = handler 69 return c 70 } 71 return &NoticeHandlerConnector{Connector: c, noticeHandler: handler} 72 } 73