CREATE OR REPLACE FUNCTION public.get_token() RETURNS text AS $$
BEGIN
    RETURN text(pg_current_wal_insert_lsn());
END;
$$ LANGUAGE plpgsql;


CREATE OR REPLACE FUNCTION public.check_token(token text) RETURNS boolean AS $$
DECLARE
    is_recovery boolean;
    head pg_lsn;
BEGIN
    SELECT pg_is_in_recovery(), pg_last_wal_replay_lsn() INTO is_recovery, head;

    IF is_recovery OR head is NULL THEN
        BEGIN
            SELECT pg_current_wal_insert_lsn() INTO head;
        EXCEPTION
            WHEN object_not_in_prerequisite_state THEN
                RETURN false;
        END;
    END IF;

    RETURN head >= pg_lsn(token);
END;
$$ LANGUAGE plpgsql;