Guest User

Row Lock

a guest
Apr 11th, 2023
248
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.86 KB | None | 0 0
  1. CREATE OR REPLACE FUNCTION process_queue() RETURNS VOID AS $$
  2. DECLARE
  3. message RECORD;
  4. BEGIN
  5. LOOP
  6. -- Get the next message in the queue, locking the row for update to avoid race conditions
  7. SELECT *
  8. INTO message
  9. FROM message_queue
  10. WHERE status = 'queued'
  11. ORDER BY created_at
  12. FOR UPDATE
  13. SKIP LOCKED
  14. LIMIT 1;
  15.  
  16. -- If there are no more messages in the queue, exit the loop
  17. IF NOT FOUND THEN
  18. EXIT;
  19. END IF;
  20.  
  21. -- Process the message
  22. -- ...
  23.  
  24. -- Update the message status to mark it as processed
  25. UPDATE message_queue
  26. SET status = 'processed', processed_at = NOW()
  27. WHERE id = message.id;
  28.  
  29. -- Commit the transaction to release the lock
  30. COMMIT;
  31. END LOOP;
  32. END;
  33. $$ LANGUAGE plpgsql;
  34.  
Advertisement
Add Comment
Please, Sign In to add comment