-- complain if script is sourced in psql, rather than via CREATE EXTENSION
\echo Use "CREATE EXTENSION wal2sql" to load this file. \quit

--
-- Event trigger function to capture DDL commands and emit them into the
-- logical replication stream via pg_logical_emit_message().
--
-- This function is called by the wal2sql_ddl_trigger event trigger on
-- ddl_command_end events. It captures the DDL command text and emits it
-- with the 'ddl' prefix so it will be picked up by the wal2sql logical
-- decoding plugin's message_cb callback.
--
CREATE FUNCTION wal2sql_ddl_handler()
RETURNS event_trigger
LANGUAGE plpgsql
AS $$
DECLARE
    ddl_command text;
BEGIN
    -- Get the current query text (the DDL command being executed)
    ddl_command := current_query();

    -- Emit the DDL command into the logical replication stream.
    -- Parameters:
    --   transactional = true: message is part of current transaction
    --   prefix = 'ddl': identifies this as a DDL message for wal2sql plugin
    --   content = ddl_command: the actual DDL SQL text
    PERFORM pg_logical_emit_message(true, 'ddl', ddl_command);
END;
$$;

--
-- Event trigger that fires on DDL command completion
--
-- This trigger fires after any DDL command completes successfully,
-- calling wal2sql_ddl_handler() to emit the command into the replication stream.
--
CREATE EVENT TRIGGER wal2sql_ddl_trigger
ON ddl_command_end
EXECUTE FUNCTION wal2sql_ddl_handler();
