[][src]Function pgx::callbacks::register_xact_callback

pub fn register_xact_callback<F>(
    which_event: PgXactCallbackEvent,
    f: F
) -> XactCallbackReceipt where
    F: FnOnce() + UnwindSafe + RefUnwindSafe + 'static, 

Register a closure to be called during one of the PgXactCallbackEvent events. Multiple closures can be registered per event (one at a time), and they are called in the order in which they were registered.

Registered callbacks only remain registered for the life of a single transaction. Registration of permanet callbacks should be done through the unsafe pg_sys::RegisterXactCallback() function.

Examples

Register a number of events for pre-commit and commit:

use pgx::*;

register_xact_callback(PgXactCallbackEvent::PreCommit, || info!("pre-commit #1"));
register_xact_callback(PgXactCallbackEvent::PreCommit, || info!("pre-commit #2"));
register_xact_callback(PgXactCallbackEvent::PreCommit, || info!("pre-commit #3"));
register_xact_callback(PgXactCallbackEvent::Commit, || info!("called after commit"));

Register an event, do some work, and then decide the callback isn't actually necessary anymore:

use pgx::*;

// ... do some initialization work ...

let receipt = register_xact_callback(PgXactCallbackEvent::Abort, || { /* do cleanup if xact aborts */});

// ... do work that might abort the transaction ...

// if we got here, the transaction did not abort, so we no longer need to care about cleanup
receipt.unregister_callback();

Safety

Any kind of Rust panic!() or Postgres ereport(ERROR) while executing a PgXactCallbackEvent::Commit or PgXactCallbackEvent::Abort event will immediately cause the Postgres backend to abort and the entire cluster to restart.

As the Postgres internal documentation says:

At transaction end, the callback occurs post-commit or post-abort, so the callback functions can only do noncritical cleanup.