Repository navigation
Expand file tree
/
Copy pathcreate-queue-infrastructure.sql
More file actions
66 lines (57 loc) · 1.95 KB
/
Copy pathcreate-queue-infrastructure.sql
File metadata and controls
66 lines (57 loc) · 1.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
-- Create missing queue infrastructure
-- This creates the proper queue table structure and RPC functions
-- 1. Add missing columns to notification_queue table
ALTER TABLE public.notification_queue ADD COLUMN IF NOT EXISTS queue_name TEXT;
ALTER TABLE public.notification_queue ADD COLUMN IF NOT EXISTS visible_at TIMESTAMPTZ DEFAULT NOW();
ALTER TABLE public.notification_queue ADD COLUMN IF NOT EXISTS processing_started_at TIMESTAMPTZ;
-- 2. Create index for efficient queue processing
CREATE INDEX IF NOT EXISTS idx_notification_queue_visibility
ON public.notification_queue(queue_name, visible_at)
WHERE processed_at IS NULL;
-- 3. Create the dequeue RPC function
CREATE OR REPLACE FUNCTION dequeue_notification_job(
p_queue_name TEXT,
p_visibility_timeout INTEGER DEFAULT 30
)
RETURNS TABLE (
id UUID,
queue_name TEXT,
message JSONB,
created_at TIMESTAMPTZ
)
LANGUAGE plpgsql
AS $$
DECLARE
job_record RECORD;
visibility_deadline TIMESTAMPTZ;
BEGIN
visibility_deadline := NOW() + (p_visibility_timeout || ' seconds')::INTERVAL;
-- Find and lock the next available job
SELECT nq.id, nq.queue_name, nq.message, nq.created_at
INTO job_record
FROM public.notification_queue nq
WHERE nq.queue_name = p_queue_name
AND nq.visible_at <= NOW()
AND nq.processed_at IS NULL
AND (nq.processing_started_at IS NULL OR nq.processing_started_at < NOW() - INTERVAL '60 seconds')
ORDER BY nq.visible_at ASC
LIMIT 1
FOR UPDATE SKIP LOCKED;
IF FOUND THEN
-- Mark as being processed
UPDATE public.notification_queue
SET processing_started_at = NOW()
WHERE notification_queue.id = job_record.id;
-- Return the job
RETURN QUERY SELECT
job_record.id,
job_record.queue_name,
job_record.message,
job_record.created_at;
END IF;
RETURN;
END;
$$;
-- 4. Grant permissions
GRANT EXECUTE ON FUNCTION dequeue_notification_job(TEXT, INTEGER) TO service_role;
-- Queue infrastructure setup complete!