Dette er en prototype af en indpakning, der dårligt emulerer DBMS_LOCK.REQUEST
- begrænset til kun én type lås (rådgivningslås for transaktionsomfang).
For at gøre funktionen fuldt ud kompatibel med Oracle's ville den have brug for flere hundrede linjer. Men det er en begyndelse.
CREATE OR REPLACE FUNCTION
advisory_xact_lock_request(p_key bigint, p_timeout numeric)
RETURNS integer
LANGUAGE plpgsql AS $$
/* Imitate DBMS_LOCK.REQUEST for PostgreSQL advisory lock.
Return 0 on Success, 1 on Timeout, 3 on Parameter Error. */
DECLARE
t0 timestamptz := clock_timestamp();
BEGIN
IF p_timeout NOT BETWEEN 0 AND 86400 THEN
RAISE WARNING 'Invalid timeout parameter';
RETURN 3;
END IF;
LOOP
IF pg_try_advisory_xact_lock(key) THEN
RETURN 0;
ELSIF clock_timestamp() > t0 + (p_timeout||' seconds')::interval THEN
RAISE WARNING 'Could not acquire lock in % seconds', p_timeout;
RETURN 1;
ELSE
PERFORM pg_sleep(0.01); /* 10 ms */
END IF;
END LOOP;
END;
$$;
Test det med denne kode:
SELECT CASE
WHEN advisory_xact_lock_request(1, 2.5) = 0
THEN pg_sleep(120)
END; -- and repeat this in parallel session
/* Usage in Pl/PgSQL */
lkstat := advisory_xact_lock_request(lkhndl, lktimeout);