Advertisement
exapsy

psql_notify

May 20th, 2024 (edited)
521
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 1.17 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4.     "context"
  5.     "fmt"
  6.     "time"
  7.  
  8.     "github.com/jackc/pgx/v5/pgxpool"
  9. )
  10.  
  11. const PSQL_HOST = "postgresql://root:root@mysrv.dev/test"
  12.  
  13. func main() {
  14.     ctx := context.Background()
  15.  
  16.     dbconfig, err := pgxpool.ParseConfig(PSQL_HOST)
  17.     if err != nil {
  18.         panic(err)
  19.     }
  20.  
  21.     pool, err := pgxpool.NewWithConfig(context.Background(), dbconfig)
  22.     if err != nil {
  23.         panic(err)
  24.     }
  25.     // defer pool.Close()
  26.  
  27.     go func() {
  28.         _, err := pool.Exec(ctx, "listen test")
  29.         if err != nil {
  30.             panic(err)
  31.         }
  32.  
  33.         conn, err := pool.Acquire(ctx)
  34.         if err != nil {
  35.             panic(err)
  36.         }
  37.  
  38.         fmt.Println("Listening for notifications")
  39.         notification, err := conn.Conn().WaitForNotification(ctx)
  40.         if err != nil {
  41.             panic("Error waiting for notification: " + err.Error())
  42.         }
  43.  
  44.         for notification != nil {
  45.             fmt.Println("Received notification:", notification)
  46.         }
  47.     }()
  48.  
  49.     pool.Exec(ctx, "CREATE TABLE IF NOT EXISTS test (key TEXT PRIMARY KEY, value TEXT)")
  50.     pool.Exec(ctx, "INSERT INTO test (key, value) VALUES ('key', 'value')")
  51.     go func() {
  52.         ticker := time.NewTicker(5 * time.Second)
  53.         for range ticker.C {
  54.             pool.Exec(ctx, "NOTIFY test")
  55.         }
  56.     }()
  57.  
  58.     for {
  59.     }
  60. }
  61.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement