@@ -5,52 +5,69 @@ package main
55
66import (
77 " context"
8+ " fmt"
89 " log"
10+ " time"
911
10- " github.com/kyleconroy/pgoutput"
1112 " github.com/jackc/pgx"
13+ " github.com/kyleconroy/pgoutput"
1214)
1315
1416func main () {
1517 ctx := context.Background ()
16- config := pgx.ConnConfig {Database: " db " , User: " replicant" }
18+ config := pgx.ConnConfig {Database: " opsdash " , User: " replicant" }
1719 conn , err := pgx.ReplicationConnect (config)
1820 if err != nil {
1921 log.Fatal (err)
2022 }
2123
22- err = conn. StartReplication ( " sub1 " , 0 , - 1 , ` ("proto_version" '1', "publication_names" 'pub1') ` )
23- if err != nil {
24- log.Fatalf (" Failed to start replication: %v " , err)
25- }
24+ // Create a slot if it doesn't already exist
25+ // if err := conn.CreateReplicationSlot("sub2", "pgoutput"); err != nil {
26+ // log.Fatalf("Failed to create replication slot : %v", err)
27+ // }
2628
2729 set := pgoutput.NewRelationSet ()
28- for {
29- var message *pgx. ReplicationMessage
30- message , err = conn. WaitForReplicationMessage (ctx )
30+
31+ dump := func (relation uint32 , row []pgoutput. Tuple ) error {
32+ values , err := set. Values (relation, row )
3133 if err != nil {
32- log.Fatalf (" Replication failed: %v %s " , err)
33- }
34- if message.WalMessage == nil {
35- continue
34+ return fmt.Errorf (" error parsing values: %s " , err)
3635 }
37- m , err := pgoutput. Parse (message. WalMessage . WalData )
38- if err != nil {
39- log.Fatalf ( " error parsing waldata : %s " , err )
36+ for name , value := range values {
37+ val := value. Get ()
38+ log.Printf ( " %s ( %T ) : %#v " , name, val, val )
4039 }
40+ return nil
41+ }
42+
43+ handler := func (m pgoutput.Message ) error {
4144 switch v := m.(type ) {
4245 case pgoutput.Relation :
46+ log.Printf (" RELATION" )
4347 set.Add (v)
4448 case pgoutput.Insert :
45- values , err := set. Values (v. RelationID , v. Row )
46- if err != nil {
47- log. Fatalf ( " error parsing values: %s " , err)
48- }
49- for name , value := range values {
50- val := value. Get ()
51- log.Printf (" %s ( %T ): %#v " , name, val, val )
52- }
49+ log. Printf ( " INSERT " )
50+ return dump (v. RelationID , v. Row )
51+ case pgoutput. Update :
52+ log. Printf ( " UPDATE " )
53+ return dump (v. RelationID , v. Row )
54+ case pgoutput. Delete :
55+ log.Printf (" DELETE " )
56+ return dump (v. RelationID , v. Row )
5357 }
58+ return nil
59+ }
60+
61+ replication := pgoutput.LogicalReplication {
62+ Subscription: " sub2" ,
63+ Publication: " pub2" ,
64+ WaitTimeout: time.Second * 10 ,
65+ StatusTimeout: time.Second * 10 ,
66+ Handler: handler,
67+ }
68+
69+ if err := replication.Start (ctx, conn); err != nil {
70+ log.Fatal (err)
5471 }
5572}
5673```
0 commit comments