Created
April 2, 2011 06:17
-
-
Save ryandotsmith/899283 to your computer and use it in GitHub Desktop.
lock_head with ctids
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CREATE OR REPLACE FUNCTION lock_head() RETURNS SETOF jobs AS $$ | |
DECLARE | |
unlocked integer; | |
job jobs%rowtype; | |
BEGIN | |
SELECT id INTO unlocked | |
FROM jobs | |
WHERE locked_at IS NULL | |
AND ctid = any(array(SELECT ctid FROM jobs LIMIT 10)) | |
LIMIT 1 | |
FOR UPDATE; | |
RETURN QUERY UPDATE jobs | |
SET locked_at = (CURRENT_TIMESTAMP) | |
WHERE id = unlocked AND locked_at IS NULL | |
RETURNING *; | |
END; | |
$$ LANGUAGE plpgsql; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment