· last year · May 20, 2024, 07:45 AM
1package main
2
3import (
4 "context"
5 "fmt"
6 "time"
7
8 "github.com/jackc/pgx/v5/pgxpool"
9)
10
11const PSQL_HOST = "postgresql://root:root@mysrv.dev/test"
12
13func 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