Skip to content

Instantly share code, notes, and snippets.

@Bert-R
Last active March 25, 2023 17:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Bert-R/5de9219296f9092e980f9f5817df493c to your computer and use it in GitHub Desktop.
Save Bert-R/5de9219296f9092e980f9f5817df493c to your computer and use it in GitHub Desktop.
Logical replication using text_decoding and pgoutput

Commands to play with logical replication

Using test_decoding plug-in

SELECT pg_create_logical_replication_slot('demo_slot', 'test_decoding');

SELECT pg_logical_emit_message(true, 'context', 'Hello World!');

SELECT pg_logical_slot_peek_changes('demo_slot', NULL, NULL, 'include-xids', '0');

SELECT pg_logical_slot_get_changes('demo_slot', NULL, NULL);

SELECT pg_drop_replication_slot('demo_slot');

Using pgoutput plug-in

-- For emited messages, it is OK to use a nonexisting publication from pg_logical_slot_(peek|get)_binary_changes,
-- but if other changes are published, peek and get fail with 'publication does not exist'.
CREATE PUBLICATION SomePublication; 
SELECT pg_create_logical_replication_slot('pgout_slot','pgoutput');

SELECT pg_logical_emit_message(true, 'aContext', 'a transactional message');

SELECT get_byte(data, 1), encode(substr(data, 23, 23), 'escape')  FROM pg_logical_slot_peek_binary_changes('pgout_slot', NULL, NULL, 'proto_version', '1', 'publication_names', 'SomePublication', 'messages', 'true') OFFSET 1 LIMIT 1;

-- Next call clears the change log but does not return any data
SELECT pg_logical_slot_get_binary_changes('pgout_slot', NULL, NULL, 'proto_version', '1', 'publication_names', 'SomePublication');

SELECT pg_drop_replication_slot('pgout_slot');
DROP PUBLICATION SomePublication;

List replication slots and publications

SELECT * FROM pg_replication_slots;
SELECT * FROM pg_publication;

Relevant links:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment