@@ -11,6 +11,7 @@ import (
1111 "crypto/sha256"
1212 "database/sql"
1313 "encoding/binary"
14+ "encoding/hex"
1415 "encoding/json"
1516 "fmt"
1617 "strconv"
@@ -34,7 +35,7 @@ type databaseListener interface {
3435 // Listen starts listening for database notifications
3536 Listen (context.Context ) error
3637 // Handle registers a handler for notifications on a specific table
37- Handle (string , pgxlisten.Handler )
38+ Handle (channelName string , handler pgxlisten.Handler )
3839}
3940
4041// Notifier implements a simple subscription API to listen for updates on a database table.
@@ -69,6 +70,9 @@ type Notifier struct {
6970 listenerWg sync.WaitGroup
7071 // closed indicates whether the notifier has been closed
7172 closed bool
73+ // channelName is the name of the channel on which to receive notifications.
74+ // It must be smaller than 63 characters per Postgres limit
75+ channelName string
7276}
7377
7478var logger = logging .MustGetLogger ()
@@ -121,6 +125,8 @@ func NewNotifier(
121125 },
122126 }
123127
128+ channelName := pgChannelName (table )
129+
124130 n := & Notifier {
125131 writeDB : writeDB ,
126132 table : table ,
@@ -131,10 +137,11 @@ func NewNotifier(
131137 cancel : cancel ,
132138 listenerErr : make (chan error , 1 ), // buffered to prevent blocking
133139 closed : false ,
140+ channelName : channelName ,
134141 }
135142
136143 // attach handler that calls the subscribers
137- n .listener .Handle (table , & notificationHandler {
144+ n .listener .Handle (channelName , & notificationHandler {
138145 table : table ,
139146 primaryKeys : primaryKeys ,
140147 callback : n .dispatch ,
@@ -313,7 +320,7 @@ func (db *Notifier) GetSchema() string {
313320 lock ,
314321 funcName ,
315322 concatenateIDs (primaryKeys ),
316- db .table ,
323+ db .channelName ,
317324 db .table ,
318325 convertOperations (db .notifyOperations ), db .table ,
319326 funcName ,
@@ -346,8 +353,8 @@ func (a *listenerAdapter) Listen(ctx context.Context) error {
346353}
347354
348355// Handle delegates to the wrapped listener
349- func (a * listenerAdapter ) Handle (table string , handler pgxlisten.Handler ) {
350- a .Listener .Handle (table , handler )
356+ func (a * listenerAdapter ) Handle (channelName string , handler pgxlisten.Handler ) {
357+ a .Listener .Handle (channelName , handler )
351358}
352359
353360// notificationHandler handles database notifications and invokes subscribers
@@ -435,3 +442,10 @@ func createLockTag(m string) int64 {
435442
436443 return int64 (binary .BigEndian .Uint64 (h [:])) //nolint:gosec
437444}
445+
446+ func pgChannelName (input string ) string {
447+ const prefix = "notify_"
448+ sum := sha256 .Sum256 ([]byte (input ))
449+
450+ return prefix + hex .EncodeToString (sum [:])[:16 ] // 23 chars total
451+ }
0 commit comments