SELECT pg_try_advisory_lock(2)::integer as gotlock \gset
\if :gotlock

SELECT pg_advisory_lock(42);
        alter table p detach partition p2 concurrently ;
        alter table p detach partition p4 concurrently ;
select pg_advisory_unlock(42);

\set var random(1, 5000)
\sleep :var us

alter table p attach partition p2 for values from (1) to (2);
alter table p attach partition p4 for values from (3) to (4);

select nextval('detaches');

\endif
