pgbus 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2354 @@
1
+ ------------------------------------------------------------
2
+ -- Schema, tables, records, privileges, indexes, etc
3
+ ------------------------------------------------------------
4
+ -- A pre-existing pgmq schema may be writable by a queue creator. Resolve
5
+ -- defaults and generated expressions against trusted built-ins during install.
6
+ -- A local setting lasts through a transaction (including CREATE EXTENSION).
7
+ -- If this file is run statement by statement, the next block detects that the
8
+ -- local setting expired and uses a session setting until the closing block.
9
+ DO $pgmq_install_path$
10
+ BEGIN
11
+ PERFORM pg_catalog.set_config('search_path', 'pg_catalog, pg_temp', true);
12
+ END
13
+ $pgmq_install_path$;
14
+
15
+ DO $pgmq_install_path$
16
+ DECLARE
17
+ active_path pg_catalog.text := pg_catalog.current_setting('search_path');
18
+ BEGIN
19
+ IF NOT (active_path OPERATOR(pg_catalog.=) 'pg_catalog, pg_temp'::pg_catalog.text) THEN
20
+ PERFORM pg_catalog.set_config('pgmq.install_saved_search_path', active_path, false);
21
+ PERFORM pg_catalog.set_config('pgmq.install_path_override', '1', false);
22
+ PERFORM pg_catalog.set_config('search_path', 'pg_catalog, pg_temp', false);
23
+ END IF;
24
+ END
25
+ $pgmq_install_path$;
26
+
27
+ -- When installed as an extension, we don't need to create the `pgmq` schema
28
+ -- because it is automatically created by postgres due to being declared in
29
+ -- the extension control file
30
+ DO
31
+ $$
32
+ BEGIN
33
+ IF (SELECT NOT EXISTS( SELECT 1 FROM pg_extension WHERE extname = 'pgmq')) THEN
34
+ CREATE SCHEMA IF NOT EXISTS pgmq;
35
+ END IF;
36
+ END
37
+ $$;
38
+
39
+ -- Table where queues and metadata about them is stored
40
+ CREATE TABLE IF NOT EXISTS pgmq.meta (
41
+ queue_name VARCHAR UNIQUE NOT NULL,
42
+ is_partitioned BOOLEAN NOT NULL,
43
+ is_unlogged BOOLEAN NOT NULL,
44
+ created_at TIMESTAMP WITH TIME ZONE DEFAULT now() NOT NULL
45
+ );
46
+
47
+ -- pg_monitor can list queues (pgmq.list_queues / pgmq.meta) and compute queue metrics
48
+ -- (pgmq.metrics / pgmq.metrics_all), but it must not read message payloads. It therefore gets
49
+ -- USAGE on the schema and SELECT on pgmq.meta only; the per-queue create functions additionally
50
+ -- grant column-level SELECT on the metrics columns (vt, enqueued_at) of each queue table and
51
+ -- SELECT on the queue's msg_id sequence. It is intentionally NOT granted SELECT on the queue or
52
+ -- archive tables (which hold application data) nor on their message/headers columns.
53
+ -- These grants are intentionally placed here (after creating `pgmq.meta` but before creating other tables). This
54
+ -- allows the `pg_dump` output for a fresh installation to match the output for an installation that followed the
55
+ -- upgrade path.
56
+ GRANT USAGE ON SCHEMA pgmq TO pg_monitor;
57
+ GRANT SELECT ON pgmq.meta TO pg_monitor;
58
+
59
+ -- Table to track notification throttling for queues
60
+ CREATE UNLOGGED TABLE IF NOT EXISTS pgmq.notify_insert_throttle (
61
+ queue_name VARCHAR UNIQUE NOT NULL -- Queue name (without 'q_' prefix)
62
+ CONSTRAINT notify_insert_throttle_meta_queue_name_fk
63
+ REFERENCES pgmq.meta (queue_name)
64
+ ON DELETE CASCADE,
65
+ throttle_interval_ms INTEGER NOT NULL DEFAULT 0, -- Min milliseconds between notifications (0 = no throttling)
66
+ last_notified_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT pg_catalog.to_timestamp(0) -- Timestamp of last sent notification
67
+ );
68
+
69
+ CREATE INDEX IF NOT EXISTS idx_notify_throttle_active
70
+ ON pgmq.notify_insert_throttle (queue_name, last_notified_at)
71
+ WHERE throttle_interval_ms > 0;
72
+
73
+ CREATE TABLE IF NOT EXISTS pgmq.topic_bindings
74
+ (
75
+ pattern text NOT NULL, -- Wildcard pattern for routing key matching (* = one segment, # = zero or more segments)
76
+ queue_name text NOT NULL -- Name of the queue that receives messages when pattern matches
77
+ CONSTRAINT topic_bindings_meta_queue_name_fk
78
+ REFERENCES pgmq.meta (queue_name)
79
+ ON DELETE CASCADE,
80
+ bound_at TIMESTAMP WITH TIME ZONE DEFAULT now() NOT NULL, -- Timestamp when the binding was created
81
+ compiled_regex text GENERATED ALWAYS AS (
82
+ -- Pre-compile the pattern to regex for faster matching
83
+ -- This avoids runtime compilation on every send_topic call
84
+ '^' ||
85
+ replace(
86
+ replace(
87
+ regexp_replace(pattern, '([.+?{}()|\[\]\\^$])', '\\\1', 'g'),
88
+ '*', '[^.]+'
89
+ ),
90
+ '#', '.*'
91
+ ) || '$'
92
+ ) STORED, -- Computed column: stores the compiled regex pattern
93
+ CONSTRAINT topic_bindings_unique_pattern_queue UNIQUE (pattern, queue_name)
94
+ );
95
+
96
+ -- Create covering index for better performance when scanning patterns
97
+ -- Includes queue_name and compiled_regex to allow index-only scans (no table access needed)
98
+ CREATE INDEX IF NOT EXISTS idx_topic_bindings_covering ON pgmq.topic_bindings (pattern) INCLUDE (queue_name, compiled_regex);
99
+
100
+ -- Allow the following `pgmq` tables to be dumped by `pg_dump` when pgmq is installed as an extension
101
+ DO
102
+ $$
103
+ BEGIN
104
+ IF EXISTS(SELECT 1 FROM pg_extension WHERE extname = 'pgmq') THEN
105
+ PERFORM pg_catalog.pg_extension_config_dump('pgmq.meta', '');
106
+ PERFORM pg_catalog.pg_extension_config_dump('pgmq.notify_insert_throttle', '');
107
+ PERFORM pg_catalog.pg_extension_config_dump('pgmq.topic_bindings', '');
108
+ END IF;
109
+ END
110
+ $$;
111
+
112
+ -- This type has the shape of a message in a queue, and is often returned by
113
+ -- pgmq functions that return messages.
114
+ -- Note: Changing the order of fields in this type is a breaking change -- our Rust Diesel client implementation
115
+ -- expects a specific order of fields.
116
+ CREATE TYPE pgmq.message_record AS (
117
+ msg_id BIGINT,
118
+ read_ct INTEGER,
119
+ enqueued_at TIMESTAMP WITH TIME ZONE,
120
+ last_read_at TIMESTAMP WITH TIME ZONE,
121
+ vt TIMESTAMP WITH TIME ZONE,
122
+ message JSONB,
123
+ headers JSONB
124
+ );
125
+
126
+ -- Note: Changing the order of fields in this type is a breaking change -- our Rust Diesel client implementation
127
+ -- expects a specific order of fields.
128
+ CREATE TYPE pgmq.queue_record AS (
129
+ queue_name VARCHAR,
130
+ is_partitioned BOOLEAN,
131
+ is_unlogged BOOLEAN,
132
+ created_at TIMESTAMP WITH TIME ZONE
133
+ );
134
+
135
+ ------------------------------------------------------------
136
+ -- Functions
137
+ ------------------------------------------------------------
138
+
139
+ -- Convention: functions below are SECURITY INVOKER and pin
140
+ -- `SET search_path = pg_catalog, pg_temp` so that unqualified references to
141
+ -- built-in functions, operators, casts and types (and the dynamic SQL these
142
+ -- functions run) resolve against a fixed, non-caller-controlled path rather
143
+ -- than the caller's search_path. Keep this clause on any new function, and on
144
+ -- the notify_queue_listeners trigger function, which runs implicitly under the
145
+ -- inserting role's search_path. The two public partition wrappers are the
146
+ -- exception: their pinned internal implementations call pg_partman, which
147
+ -- changes the session search_path; the wrappers restore the caller's path.
148
+ -- Internal calls into pgmq also use exact argument types to prevent an
149
+ -- attacker-created overload in pgmq from winning. See the security tests.
150
+
151
+ -- prevents race conditions during queue creation by acquiring a transaction-level advisory lock
152
+ -- uses a transaction advisory lock maintain the lock until transaction commit
153
+ -- a race condition would still exist if lock was released before commit
154
+ CREATE FUNCTION pgmq.acquire_queue_lock(queue_name TEXT)
155
+ RETURNS void AS $$
156
+ BEGIN
157
+ PERFORM pg_catalog.pg_advisory_xact_lock(pg_catalog.hashtext('pgmq.queue_' || queue_name));
158
+ END;
159
+ $$ LANGUAGE plpgsql SET search_path = pg_catalog, pg_temp;
160
+
161
+ -- read_grouped_round_robin
162
+ -- reads messages while preserving FIFO within groups and interleaving across groups (layered round-robin)
163
+ CREATE FUNCTION pgmq.read_grouped_rr(
164
+ queue_name TEXT,
165
+ vt INTEGER,
166
+ qty INTEGER
167
+ )
168
+ RETURNS SETOF pgmq.message_record AS $$
169
+ DECLARE
170
+ sql TEXT;
171
+ qtable TEXT := pgmq.format_table_name(queue_name, 'q'::pg_catalog.text);
172
+ BEGIN
173
+ sql := FORMAT(
174
+ $QUERY$
175
+ WITH fifo_groups AS (
176
+ -- Determine the absolute head (oldest) message id per FIFO group, regardless of visibility
177
+ SELECT
178
+ COALESCE(headers->>'x-pgmq-group', '_default_fifo_group') AS fifo_key,
179
+ MIN(msg_id) AS head_msg_id
180
+ FROM pgmq.%1$I
181
+ GROUP BY COALESCE(headers->>'x-pgmq-group', '_default_fifo_group')
182
+ ),
183
+ eligible_groups AS (
184
+ -- Only groups whose head message is currently visible
185
+ -- Acquire a transaction-level advisory lock per group to prevent concurrent selection
186
+ SELECT
187
+ g.fifo_key,
188
+ g.head_msg_id,
189
+ ROW_NUMBER() OVER (ORDER BY g.head_msg_id) AS group_priority
190
+ FROM fifo_groups g
191
+ JOIN pgmq.%2$I h ON h.msg_id = g.head_msg_id
192
+ WHERE h.vt <= clock_timestamp()
193
+ AND pg_try_advisory_xact_lock(pg_catalog.hashtextextended(g.fifo_key, 0))
194
+ ),
195
+ available_messages AS (
196
+ -- All currently visible messages starting at the head for each eligible group
197
+ SELECT
198
+ m.msg_id,
199
+ eg.group_priority,
200
+ ROW_NUMBER() OVER (
201
+ PARTITION BY eg.fifo_key
202
+ ORDER BY m.msg_id
203
+ ) AS msg_rank_in_group
204
+ FROM pgmq.%3$I m
205
+ JOIN eligible_groups eg
206
+ ON COALESCE(m.headers->>'x-pgmq-group', '_default_fifo_group') = eg.fifo_key
207
+ WHERE m.vt <= clock_timestamp()
208
+ AND m.msg_id >= eg.head_msg_id
209
+ ),
210
+ ordered_messages AS (
211
+ -- Layered round-robin: take rank 1 of all groups by group_priority, then rank 2, etc.
212
+ -- Assign selection order before locking
213
+ SELECT msg_id, ROW_NUMBER() OVER (ORDER BY msg_rank_in_group, group_priority) as selection_order
214
+ FROM available_messages
215
+ ),
216
+ selected_messages AS (
217
+ -- Lock the messages in the correct order, preserving selection_order
218
+ SELECT om.msg_id, om.selection_order
219
+ FROM ordered_messages om
220
+ JOIN pgmq.%4$I m ON m.msg_id = om.msg_id
221
+ WHERE om.selection_order <= $1
222
+ ORDER BY om.selection_order
223
+ FOR UPDATE OF m SKIP LOCKED
224
+ ),
225
+ updated_messages AS (
226
+ UPDATE pgmq.%5$I m
227
+ SET
228
+ vt = clock_timestamp() + %6$L,
229
+ read_ct = read_ct + 1,
230
+ last_read_at = clock_timestamp()
231
+ FROM selected_messages sm
232
+ WHERE m.msg_id = sm.msg_id
233
+ AND m.vt <= clock_timestamp() -- final guard to avoid duplicate reads under races
234
+ RETURNING m.msg_id, m.read_ct, m.enqueued_at, m.last_read_at, m.vt, m.message, m.headers, sm.selection_order
235
+ )
236
+ SELECT msg_id, read_ct, enqueued_at, last_read_at, vt, message, headers
237
+ FROM updated_messages
238
+ ORDER BY selection_order;
239
+ $QUERY$,
240
+ qtable, qtable, qtable, qtable, qtable, pg_catalog.make_interval(secs => vt)
241
+ );
242
+ RETURN QUERY EXECUTE sql USING qty;
243
+ END;
244
+ $$ LANGUAGE plpgsql SET search_path = pg_catalog, pg_temp;
245
+
246
+ -- read_grouped_rr_with_poll
247
+ -- reads messages using round-robin layering across groups, with polling support
248
+ CREATE FUNCTION pgmq.read_grouped_rr_with_poll(
249
+ queue_name TEXT,
250
+ vt INTEGER,
251
+ qty INTEGER,
252
+ max_poll_seconds INTEGER DEFAULT 5,
253
+ poll_interval_ms INTEGER DEFAULT 100
254
+ )
255
+ RETURNS SETOF pgmq.message_record AS $$
256
+ DECLARE
257
+ r pgmq.message_record;
258
+ stop_at TIMESTAMP;
259
+ BEGIN
260
+ stop_at := clock_timestamp() + pg_catalog.make_interval(secs => max_poll_seconds);
261
+ LOOP
262
+ IF (SELECT clock_timestamp() >= stop_at) THEN
263
+ RETURN;
264
+ END IF;
265
+
266
+ FOR r IN
267
+ SELECT * FROM pgmq.read_grouped_rr(queue_name, vt, qty)
268
+ LOOP
269
+ RETURN NEXT r;
270
+ END LOOP;
271
+ IF FOUND THEN
272
+ RETURN;
273
+ ELSE
274
+ PERFORM pg_catalog.pg_sleep(poll_interval_ms::numeric / 1000);
275
+ END IF;
276
+ END LOOP;
277
+ END;
278
+ $$ LANGUAGE plpgsql SET search_path = pg_catalog, pg_temp;
279
+
280
+ -- read_grouped_head: read the head of N different FIFO groups in a single operation.
281
+ -- This supports horizontal scaling by processing groups in parallel while ensuring message ordering is preserved per group.
282
+ CREATE FUNCTION pgmq.read_grouped_head(
283
+ queue_name TEXT,
284
+ vt INTEGER,
285
+ qty INTEGER
286
+ )
287
+ RETURNS SETOF pgmq.message_record AS $$
288
+ DECLARE
289
+ sql TEXT;
290
+ qtable TEXT := pgmq.format_table_name(queue_name, 'q'::pg_catalog.text);
291
+ BEGIN
292
+ sql := FORMAT(
293
+ $QUERY$
294
+ WITH fifo_groups AS (
295
+ -- Determine the absolute head (oldest) message id per FIFO group, regardless of visibility
296
+ SELECT
297
+ COALESCE(headers->>'x-pgmq-group', '_default_fifo_group') AS fifo_key,
298
+ MIN(msg_id) AS head_msg_id
299
+ FROM pgmq.%1$I
300
+ GROUP BY COALESCE(headers->>'x-pgmq-group', '_default_fifo_group')
301
+ ),
302
+ selected_messages AS (
303
+ -- Take at most 1 message per group
304
+ SELECT g.head_msg_id msg_id
305
+ FROM fifo_groups g
306
+ JOIN pgmq.%1$I q ON q.msg_id = g.head_msg_id
307
+ WHERE q.vt <= clock_timestamp()
308
+ ORDER BY q.msg_id
309
+ LIMIT $1
310
+ FOR UPDATE SKIP LOCKED
311
+ )
312
+ UPDATE pgmq.%1$I m
313
+ SET
314
+ vt = clock_timestamp() + %2$L,
315
+ read_ct = read_ct + 1,
316
+ last_read_at = clock_timestamp()
317
+ FROM selected_messages sm
318
+ WHERE m.msg_id = sm.msg_id
319
+ RETURNING m.msg_id, m.read_ct, m.enqueued_at, m.last_read_at, m.vt, m.message, m.headers;
320
+ $QUERY$,
321
+ qtable, pg_catalog.make_interval(secs => vt)
322
+ );
323
+ RETURN QUERY EXECUTE sql USING qty;
324
+ END;
325
+ $$ LANGUAGE plpgsql SET search_path = pg_catalog, pg_temp;
326
+
327
+ -- read_grouped_head_with_poll
328
+ -- reads the head of N different FIFO groups in a single operation, with polling support
329
+ CREATE FUNCTION pgmq.read_grouped_head_with_poll(
330
+ queue_name TEXT,
331
+ vt INTEGER,
332
+ qty INTEGER,
333
+ max_poll_seconds INTEGER DEFAULT 5,
334
+ poll_interval_ms INTEGER DEFAULT 100
335
+ )
336
+ RETURNS SETOF pgmq.message_record AS $$
337
+ DECLARE
338
+ r pgmq.message_record;
339
+ stop_at TIMESTAMPTZ;
340
+ BEGIN
341
+ stop_at := clock_timestamp() + pg_catalog.make_interval(secs => max_poll_seconds);
342
+ LOOP
343
+ IF clock_timestamp() >= stop_at THEN
344
+ RETURN;
345
+ END IF;
346
+
347
+ FOR r IN
348
+ SELECT * FROM pgmq.read_grouped_head(queue_name, vt, qty)
349
+ LOOP
350
+ RETURN NEXT r;
351
+ END LOOP;
352
+ IF FOUND THEN
353
+ RETURN;
354
+ ELSE
355
+ PERFORM pg_catalog.pg_sleep(poll_interval_ms::numeric / 1000);
356
+ END IF;
357
+ END LOOP;
358
+ END;
359
+ $$ LANGUAGE plpgsql SET search_path = pg_catalog, pg_temp;
360
+
361
+ -- a helper to format table names and check for invalid characters
362
+ CREATE FUNCTION pgmq.format_table_name(queue_name text, prefix text)
363
+ RETURNS TEXT AS $$
364
+ BEGIN
365
+ IF queue_name ~ '\$|;|--|'''
366
+ THEN
367
+ RAISE EXCEPTION 'queue name contains invalid characters: $, ;, --, or \''';
368
+ END IF;
369
+ RETURN lower(prefix || '_' || queue_name);
370
+ END;
371
+ $$ LANGUAGE plpgsql SET search_path = pg_catalog, pg_temp;
372
+
373
+ -- read
374
+ -- reads a number of messages from a queue, setting a visibility timeout on them
375
+ CREATE FUNCTION pgmq.read(
376
+ queue_name TEXT,
377
+ vt INTEGER,
378
+ qty INTEGER,
379
+ conditional JSONB DEFAULT '{}'
380
+ )
381
+ RETURNS SETOF pgmq.message_record AS $$
382
+ DECLARE
383
+ sql TEXT;
384
+ qtable TEXT := pgmq.format_table_name(queue_name, 'q'::pg_catalog.text);
385
+ BEGIN
386
+ sql := FORMAT(
387
+ $QUERY$
388
+ WITH cte AS
389
+ (
390
+ SELECT msg_id
391
+ FROM pgmq.%I
392
+ WHERE vt <= clock_timestamp() AND CASE
393
+ WHEN %L != '{}'::jsonb THEN (message @> %2$L)::integer
394
+ ELSE 1
395
+ END = 1
396
+ ORDER BY msg_id ASC
397
+ LIMIT $1
398
+ FOR UPDATE SKIP LOCKED
399
+ )
400
+ UPDATE pgmq.%I m
401
+ SET
402
+ last_read_at = clock_timestamp(),
403
+ vt = clock_timestamp() + %L,
404
+ read_ct = read_ct + 1
405
+ FROM cte
406
+ WHERE m.msg_id = cte.msg_id
407
+ RETURNING m.msg_id, m.read_ct, m.enqueued_at, m.last_read_at, m.vt, m.message, m.headers;
408
+ $QUERY$,
409
+ qtable, conditional, qtable, pg_catalog.make_interval(secs => vt)
410
+ );
411
+ RETURN QUERY EXECUTE sql USING qty;
412
+ END;
413
+ $$ LANGUAGE plpgsql SET search_path = pg_catalog, pg_temp;
414
+
415
+ -- read_grouped
416
+ -- reads messages with AWS SQS FIFO-style batch retrieval behavior
417
+ -- attempts to return as many messages as possible from the same message group
418
+ CREATE FUNCTION pgmq.read_grouped(
419
+ queue_name TEXT,
420
+ vt INTEGER,
421
+ qty INTEGER
422
+ )
423
+ RETURNS SETOF pgmq.message_record AS $$
424
+ DECLARE
425
+ sql TEXT;
426
+ qtable TEXT := pgmq.format_table_name(queue_name, 'q'::pg_catalog.text);
427
+ BEGIN
428
+ sql := FORMAT(
429
+ $QUERY$
430
+ WITH fifo_groups AS (
431
+ -- Find the minimum msg_id for each FIFO group that's ready to be processed
432
+ SELECT
433
+ COALESCE(headers->>'x-pgmq-group', '_default_fifo_group') as fifo_key,
434
+ MIN(msg_id) as min_msg_id
435
+ FROM pgmq.%I
436
+ WHERE vt <= clock_timestamp()
437
+ GROUP BY COALESCE(headers->>'x-pgmq-group', '_default_fifo_group')
438
+ ),
439
+ locked_groups AS (
440
+ -- Lock the first available message in each FIFO group
441
+ SELECT
442
+ m.msg_id,
443
+ fg.fifo_key
444
+ FROM pgmq.%I m
445
+ INNER JOIN fifo_groups fg ON
446
+ COALESCE(m.headers->>'x-pgmq-group', '_default_fifo_group') = fg.fifo_key
447
+ AND m.msg_id = fg.min_msg_id
448
+ WHERE m.vt <= clock_timestamp()
449
+ ORDER BY m.msg_id ASC
450
+ FOR UPDATE SKIP LOCKED
451
+ ),
452
+ group_priorities AS (
453
+ -- Assign priority to groups based on their oldest message
454
+ SELECT
455
+ fifo_key,
456
+ msg_id as min_msg_id,
457
+ ROW_NUMBER() OVER (ORDER BY msg_id) as group_priority
458
+ FROM locked_groups
459
+ ),
460
+ filtered_groups as (
461
+ SELECT * FROM group_priorities gp
462
+ WHERE NOT EXISTS (
463
+ -- Ensure no earlier message in this group is currently being processed
464
+ SELECT 1
465
+ FROM pgmq.%I m2
466
+ WHERE COALESCE(m2.headers->>'x-pgmq-group', '_default_fifo_group') = gp.fifo_key
467
+ AND m2.vt > clock_timestamp()
468
+ AND m2.msg_id < gp.min_msg_id
469
+ )
470
+ ),
471
+ available_messages as (
472
+ SELECT gp.fifo_key, t.msg_id,gp.group_priority,
473
+ ROW_NUMBER() OVER (PARTITION BY gp.fifo_key ORDER BY t.msg_id) as msg_rank_in_group
474
+ FROM filtered_groups gp
475
+ CROSS JOIN LATERAL (
476
+ SELECT *
477
+ FROM pgmq.%I t
478
+ WHERE COALESCE(t.headers->>'x-pgmq-group', '_default_fifo_group') = gp.fifo_key
479
+ AND t.vt <= clock_timestamp()
480
+ ORDER BY msg_id
481
+ LIMIT $1 -- tip to limit query impact, we know we need at most qty in each group
482
+ ) t
483
+ ORDER BY gp.group_priority
484
+ ),
485
+ batch_selection AS (
486
+ -- Select messages to fill batch, prioritizing earliest group
487
+ SELECT
488
+ msg_id,
489
+ ROW_NUMBER() OVER (ORDER BY group_priority, msg_rank_in_group) as overall_rank
490
+ FROM available_messages
491
+ ),
492
+ selected_messages AS (
493
+ -- Limit to requested quantity
494
+ SELECT msg_id
495
+ FROM batch_selection
496
+ WHERE overall_rank <= $1
497
+ ORDER BY msg_id
498
+ FOR UPDATE SKIP LOCKED
499
+ )
500
+ UPDATE pgmq.%I m
501
+ SET
502
+ vt = clock_timestamp() + %L,
503
+ read_ct = read_ct + 1,
504
+ last_read_at = clock_timestamp()
505
+ FROM selected_messages sm
506
+ WHERE m.msg_id = sm.msg_id
507
+ RETURNING m.msg_id, m.read_ct, m.enqueued_at, m.last_read_at, m.vt, m.message, m.headers;
508
+ $QUERY$,
509
+ qtable, qtable, qtable, qtable, qtable, pg_catalog.make_interval(secs => vt)
510
+ );
511
+ RETURN QUERY EXECUTE sql USING qty;
512
+ END;
513
+ $$ LANGUAGE plpgsql SET search_path = pg_catalog, pg_temp;
514
+
515
+ -- read_grouped_with_poll
516
+ -- reads messages with AWS SQS FIFO-style batch retrieval behavior, with polling support
517
+ CREATE FUNCTION pgmq.read_grouped_with_poll(
518
+ queue_name TEXT,
519
+ vt INTEGER,
520
+ qty INTEGER,
521
+ max_poll_seconds INTEGER DEFAULT 5,
522
+ poll_interval_ms INTEGER DEFAULT 100
523
+ )
524
+ RETURNS SETOF pgmq.message_record AS $$
525
+ DECLARE
526
+ r pgmq.message_record;
527
+ stop_at TIMESTAMP;
528
+ BEGIN
529
+ stop_at := clock_timestamp() + pg_catalog.make_interval(secs => max_poll_seconds);
530
+ LOOP
531
+ IF (SELECT clock_timestamp() >= stop_at) THEN
532
+ RETURN;
533
+ END IF;
534
+
535
+ FOR r IN
536
+ SELECT * FROM pgmq.read_grouped(queue_name, vt, qty)
537
+ LOOP
538
+ RETURN NEXT r;
539
+ END LOOP;
540
+ IF FOUND THEN
541
+ RETURN;
542
+ ELSE
543
+ PERFORM pg_catalog.pg_sleep(poll_interval_ms::numeric / 1000);
544
+ END IF;
545
+ END LOOP;
546
+ END;
547
+ $$ LANGUAGE plpgsql SET search_path = pg_catalog, pg_temp;
548
+
549
+ ---- read_with_poll
550
+ ---- reads a number of messages from a queue, setting a visibility timeout on them
551
+ CREATE FUNCTION pgmq.read_with_poll(
552
+ queue_name TEXT,
553
+ vt INTEGER,
554
+ qty INTEGER,
555
+ max_poll_seconds INTEGER DEFAULT 5,
556
+ poll_interval_ms INTEGER DEFAULT 100,
557
+ conditional JSONB DEFAULT '{}'
558
+ )
559
+ RETURNS SETOF pgmq.message_record AS $$
560
+ DECLARE
561
+ r pgmq.message_record;
562
+ stop_at TIMESTAMP;
563
+ sql TEXT;
564
+ qtable TEXT := pgmq.format_table_name(queue_name, 'q'::pg_catalog.text);
565
+ BEGIN
566
+ stop_at := clock_timestamp() + pg_catalog.make_interval(secs => max_poll_seconds);
567
+ LOOP
568
+ IF (SELECT clock_timestamp() >= stop_at) THEN
569
+ RETURN;
570
+ END IF;
571
+
572
+ sql := FORMAT(
573
+ $QUERY$
574
+ WITH cte AS
575
+ (
576
+ SELECT msg_id
577
+ FROM pgmq.%I
578
+ WHERE vt <= clock_timestamp() AND CASE
579
+ WHEN %L != '{}'::jsonb THEN (message @> %2$L)::integer
580
+ ELSE 1
581
+ END = 1
582
+ ORDER BY msg_id ASC
583
+ LIMIT $1
584
+ FOR UPDATE SKIP LOCKED
585
+ )
586
+ UPDATE pgmq.%I m
587
+ SET
588
+ last_read_at = clock_timestamp(),
589
+ vt = clock_timestamp() + %L,
590
+ read_ct = read_ct + 1
591
+ FROM cte
592
+ WHERE m.msg_id = cte.msg_id
593
+ RETURNING m.msg_id, m.read_ct, m.enqueued_at, m.last_read_at, m.vt, m.message, m.headers;
594
+ $QUERY$,
595
+ qtable, conditional, qtable, pg_catalog.make_interval(secs => vt)
596
+ );
597
+
598
+ FOR r IN
599
+ EXECUTE sql USING qty
600
+ LOOP
601
+ RETURN NEXT r;
602
+ END LOOP;
603
+ IF FOUND THEN
604
+ RETURN;
605
+ ELSE
606
+ PERFORM pg_catalog.pg_sleep(poll_interval_ms::numeric / 1000);
607
+ END IF;
608
+ END LOOP;
609
+ END;
610
+ $$ LANGUAGE plpgsql SET search_path = pg_catalog, pg_temp;
611
+
612
+ ---- archive
613
+ ---- removes a message from the queue, and sends it to the archive, where its
614
+ ---- saved permanently.
615
+ CREATE FUNCTION pgmq.archive(
616
+ queue_name TEXT,
617
+ msg_id BIGINT
618
+ )
619
+ RETURNS BOOLEAN AS $$
620
+ DECLARE
621
+ sql TEXT;
622
+ result BIGINT;
623
+ qtable TEXT := pgmq.format_table_name(queue_name, 'q'::pg_catalog.text);
624
+ atable TEXT := pgmq.format_table_name(queue_name, 'a'::pg_catalog.text);
625
+ BEGIN
626
+ sql := FORMAT(
627
+ $QUERY$
628
+ WITH archived AS (
629
+ DELETE FROM pgmq.%I
630
+ WHERE msg_id = $1
631
+ RETURNING msg_id, vt, read_ct, enqueued_at, last_read_at, message, headers
632
+ )
633
+ INSERT INTO pgmq.%I (msg_id, vt, read_ct, enqueued_at, last_read_at, message, headers)
634
+ SELECT msg_id, vt, read_ct, enqueued_at, last_read_at, message, headers
635
+ FROM archived
636
+ RETURNING msg_id;
637
+ $QUERY$,
638
+ qtable, atable
639
+ );
640
+ EXECUTE sql USING msg_id INTO result;
641
+ RETURN NOT (result IS NULL);
642
+ END;
643
+ $$ LANGUAGE plpgsql SET search_path = pg_catalog, pg_temp;
644
+
645
+ ---- archive
646
+ ---- removes an array of message ids from the queue, and sends it to the archive,
647
+ ---- where these messages will be saved permanently.
648
+ CREATE FUNCTION pgmq.archive(
649
+ queue_name TEXT,
650
+ msg_ids BIGINT[]
651
+ )
652
+ RETURNS SETOF BIGINT AS $$
653
+ DECLARE
654
+ sql TEXT;
655
+ qtable TEXT := pgmq.format_table_name(queue_name, 'q'::pg_catalog.text);
656
+ atable TEXT := pgmq.format_table_name(queue_name, 'a'::pg_catalog.text);
657
+ BEGIN
658
+ sql := FORMAT(
659
+ $QUERY$
660
+ WITH archived AS (
661
+ DELETE FROM pgmq.%I
662
+ WHERE msg_id = ANY($1)
663
+ RETURNING msg_id, vt, read_ct, enqueued_at, last_read_at, message, headers
664
+ )
665
+ INSERT INTO pgmq.%I (msg_id, vt, read_ct, enqueued_at, last_read_at, message, headers)
666
+ SELECT msg_id, vt, read_ct, enqueued_at, last_read_at, message, headers
667
+ FROM archived
668
+ RETURNING msg_id;
669
+ $QUERY$,
670
+ qtable, atable
671
+ );
672
+ RETURN QUERY EXECUTE sql USING msg_ids;
673
+ END;
674
+ $$ LANGUAGE plpgsql SET search_path = pg_catalog, pg_temp;
675
+
676
+ ---- delete
677
+ ---- deletes a message id from the queue permanently
678
+ CREATE FUNCTION pgmq.delete(
679
+ queue_name TEXT,
680
+ msg_id BIGINT
681
+ )
682
+ RETURNS BOOLEAN AS $$
683
+ DECLARE
684
+ sql TEXT;
685
+ result BIGINT;
686
+ qtable TEXT := pgmq.format_table_name(queue_name, 'q'::pg_catalog.text);
687
+ BEGIN
688
+ sql := FORMAT(
689
+ $QUERY$
690
+ DELETE FROM pgmq.%I
691
+ WHERE msg_id = $1
692
+ RETURNING msg_id
693
+ $QUERY$,
694
+ qtable
695
+ );
696
+ EXECUTE sql USING msg_id INTO result;
697
+ RETURN NOT (result IS NULL);
698
+ END;
699
+ $$ LANGUAGE plpgsql SET search_path = pg_catalog, pg_temp;
700
+
701
+ ---- delete
702
+ ---- deletes an array of message ids from the queue permanently
703
+ CREATE FUNCTION pgmq.delete(
704
+ queue_name TEXT,
705
+ msg_ids BIGINT[]
706
+ )
707
+ RETURNS SETOF BIGINT AS $$
708
+ DECLARE
709
+ sql TEXT;
710
+ qtable TEXT := pgmq.format_table_name(queue_name, 'q'::pg_catalog.text);
711
+ BEGIN
712
+ sql := FORMAT(
713
+ $QUERY$
714
+ DELETE FROM pgmq.%I
715
+ WHERE msg_id = ANY($1)
716
+ RETURNING msg_id
717
+ $QUERY$,
718
+ qtable
719
+ );
720
+ RETURN QUERY EXECUTE sql USING msg_ids;
721
+ END;
722
+ $$ LANGUAGE plpgsql SET search_path = pg_catalog, pg_temp;
723
+
724
+ -- send: actual implementation
725
+ CREATE FUNCTION pgmq.send(
726
+ queue_name TEXT,
727
+ msg JSONB,
728
+ headers JSONB,
729
+ delay TIMESTAMP WITH TIME ZONE
730
+ ) RETURNS SETOF BIGINT AS $$
731
+ DECLARE
732
+ sql TEXT;
733
+ qtable TEXT := pgmq.format_table_name(queue_name, 'q'::pg_catalog.text);
734
+ BEGIN
735
+ sql := FORMAT(
736
+ $QUERY$
737
+ INSERT INTO pgmq.%I (vt, message, headers)
738
+ VALUES ($2, $1, $3)
739
+ RETURNING msg_id;
740
+ $QUERY$,
741
+ qtable
742
+ );
743
+ RETURN QUERY EXECUTE sql USING msg, delay, headers;
744
+ END;
745
+ $$ LANGUAGE plpgsql SET search_path = pg_catalog, pg_temp;
746
+
747
+ -- send: 2 args, no delay or headers
748
+ CREATE FUNCTION pgmq.send(
749
+ queue_name TEXT,
750
+ msg JSONB
751
+ ) RETURNS SETOF BIGINT AS $$
752
+ SELECT * FROM pgmq.send(queue_name, msg, NULL::pg_catalog.jsonb, clock_timestamp());
753
+ $$ LANGUAGE sql SET search_path = pg_catalog, pg_temp;
754
+
755
+ -- send: 3 args with headers
756
+ CREATE FUNCTION pgmq.send(
757
+ queue_name TEXT,
758
+ msg JSONB,
759
+ headers JSONB
760
+ ) RETURNS SETOF BIGINT AS $$
761
+ SELECT * FROM pgmq.send(queue_name, msg, headers, clock_timestamp());
762
+ $$ LANGUAGE sql SET search_path = pg_catalog, pg_temp;
763
+
764
+ -- send: 3 args with integer delay
765
+ CREATE FUNCTION pgmq.send(
766
+ queue_name TEXT,
767
+ msg JSONB,
768
+ delay INTEGER
769
+ ) RETURNS SETOF BIGINT AS $$
770
+ SELECT * FROM pgmq.send(queue_name, msg, NULL::pg_catalog.jsonb, clock_timestamp() + pg_catalog.make_interval(secs => delay));
771
+ $$ LANGUAGE sql SET search_path = pg_catalog, pg_temp;
772
+
773
+ -- send: 3 args with timestamp
774
+ CREATE FUNCTION pgmq.send(
775
+ queue_name TEXT,
776
+ msg JSONB,
777
+ delay TIMESTAMP WITH TIME ZONE
778
+ ) RETURNS SETOF BIGINT AS $$
779
+ SELECT * FROM pgmq.send(queue_name, msg, NULL::pg_catalog.jsonb, delay);
780
+ $$ LANGUAGE sql SET search_path = pg_catalog, pg_temp;
781
+
782
+ -- send: 4 args with integer delay
783
+ CREATE FUNCTION pgmq.send(
784
+ queue_name TEXT,
785
+ msg JSONB,
786
+ headers JSONB,
787
+ delay INTEGER
788
+ ) RETURNS SETOF BIGINT AS $$
789
+ SELECT * FROM pgmq.send(queue_name, msg, headers, clock_timestamp() + pg_catalog.make_interval(secs => delay));
790
+ $$ LANGUAGE sql SET search_path = pg_catalog, pg_temp;
791
+
792
+ -- _validate_batch_params: Private function to validate batch parameters
793
+ CREATE FUNCTION pgmq._validate_batch_params(
794
+ msgs JSONB[],
795
+ headers JSONB[]
796
+ ) RETURNS void AS $$
797
+ BEGIN
798
+ -- Validate that msgs is not NULL or empty
799
+ IF msgs IS NULL OR array_length(msgs, 1) IS NULL THEN
800
+ RAISE EXCEPTION 'msgs cannot be NULL or empty';
801
+ END IF;
802
+
803
+ -- Validate that headers array length matches msgs array length if headers is provided
804
+ -- Note: array_length returns NULL for empty arrays, so we use COALESCE to treat empty arrays as length 0
805
+ IF headers IS NOT NULL AND COALESCE(array_length(headers, 1), 0) != COALESCE(array_length(msgs, 1), 0) THEN
806
+ RAISE EXCEPTION 'headers array length (%) must match msgs array length (%)',
807
+ COALESCE(array_length(headers, 1), 0), COALESCE(array_length(msgs, 1), 0);
808
+ END IF;
809
+ END;
810
+ $$ LANGUAGE plpgsql SET search_path = pg_catalog, pg_temp;
811
+
812
+ -- _send_batch: Private function that performs the actual batch insert without validation
813
+ CREATE FUNCTION pgmq._send_batch(
814
+ queue_name TEXT,
815
+ msgs JSONB[],
816
+ headers JSONB[],
817
+ delay TIMESTAMP WITH TIME ZONE
818
+ ) RETURNS SETOF BIGINT AS $$
819
+ DECLARE
820
+ sql TEXT;
821
+ qtable TEXT := pgmq.format_table_name(queue_name, 'q'::pg_catalog.text);
822
+ BEGIN
823
+ sql := FORMAT(
824
+ $QUERY$
825
+ INSERT INTO pgmq.%I (vt, message, headers)
826
+ SELECT $2, unnest($1), unnest(coalesce($3, ARRAY[]::jsonb[]))
827
+ RETURNING msg_id;
828
+ $QUERY$,
829
+ qtable
830
+ );
831
+ RETURN QUERY EXECUTE sql USING msgs, delay, headers;
832
+ END;
833
+ $$ LANGUAGE plpgsql SET search_path = pg_catalog, pg_temp;
834
+
835
+ -- send_batch: Public function with validation
836
+ CREATE FUNCTION pgmq.send_batch(
837
+ queue_name TEXT,
838
+ msgs JSONB[],
839
+ headers JSONB[],
840
+ delay TIMESTAMP WITH TIME ZONE
841
+ ) RETURNS SETOF BIGINT AS $$
842
+ BEGIN
843
+ PERFORM pgmq._validate_batch_params(msgs, headers);
844
+ RETURN QUERY SELECT * FROM pgmq._send_batch(queue_name, msgs, headers, delay);
845
+ END;
846
+ $$ LANGUAGE plpgsql SET search_path = pg_catalog, pg_temp;
847
+
848
+ -- send batch: 2 args
849
+ CREATE FUNCTION pgmq.send_batch(
850
+ queue_name TEXT,
851
+ msgs JSONB[]
852
+ ) RETURNS SETOF BIGINT AS $$
853
+ SELECT * FROM pgmq.send_batch(queue_name, msgs, NULL::pg_catalog.jsonb[], clock_timestamp());
854
+ $$ LANGUAGE sql SET search_path = pg_catalog, pg_temp;
855
+
856
+ -- send batch: 3 args with headers
857
+ CREATE FUNCTION pgmq.send_batch(
858
+ queue_name TEXT,
859
+ msgs JSONB[],
860
+ headers JSONB[]
861
+ ) RETURNS SETOF BIGINT AS $$
862
+ SELECT * FROM pgmq.send_batch(queue_name, msgs, headers, clock_timestamp());
863
+ $$ LANGUAGE sql SET search_path = pg_catalog, pg_temp;
864
+
865
+ -- send batch: 3 args with integer delay
866
+ CREATE FUNCTION pgmq.send_batch(
867
+ queue_name TEXT,
868
+ msgs JSONB[],
869
+ delay INTEGER
870
+ ) RETURNS SETOF BIGINT AS $$
871
+ SELECT * FROM pgmq.send_batch(queue_name, msgs, NULL::pg_catalog.jsonb[], clock_timestamp() + pg_catalog.make_interval(secs => delay));
872
+ $$ LANGUAGE sql SET search_path = pg_catalog, pg_temp;
873
+
874
+ -- send batch: 3 args with timestamp
875
+ CREATE FUNCTION pgmq.send_batch(
876
+ queue_name TEXT,
877
+ msgs JSONB[],
878
+ delay TIMESTAMP WITH TIME ZONE
879
+ ) RETURNS SETOF BIGINT AS $$
880
+ SELECT * FROM pgmq.send_batch(queue_name, msgs, NULL::pg_catalog.jsonb[], delay);
881
+ $$ LANGUAGE sql SET search_path = pg_catalog, pg_temp;
882
+
883
+ -- send_batch: 4 args with integer delay
884
+ CREATE FUNCTION pgmq.send_batch(
885
+ queue_name TEXT,
886
+ msgs JSONB[],
887
+ headers JSONB[],
888
+ delay INTEGER
889
+ ) RETURNS SETOF BIGINT AS $$
890
+ SELECT * FROM pgmq.send_batch(queue_name, msgs, headers, clock_timestamp() + pg_catalog.make_interval(secs => delay));
891
+ $$ LANGUAGE sql SET search_path = pg_catalog, pg_temp;
892
+
893
+ -- returned by pgmq.metrics() and pgmq.metrics_all
894
+ -- Note: Changing the order of fields in this type is a breaking change -- our Rust Diesel client implementation
895
+ -- expects a specific order of fields.
896
+ CREATE TYPE pgmq.metrics_result AS (
897
+ queue_name text,
898
+ queue_length bigint,
899
+ newest_msg_age_sec int,
900
+ oldest_msg_age_sec int,
901
+ total_messages bigint,
902
+ scrape_time timestamp with time zone,
903
+ queue_visible_length bigint,
904
+ default_partition_length bigint
905
+ );
906
+
907
+ -- get metrics for a single queue
908
+ CREATE FUNCTION pgmq.metrics(queue_name TEXT)
909
+ RETURNS pgmq.metrics_result AS $$
910
+ DECLARE
911
+ result_row pgmq.metrics_result;
912
+ query TEXT;
913
+ qtable TEXT := pgmq.format_table_name(queue_name, 'q'::pg_catalog.text);
914
+ q_default_partition TEXT := qtable || '_default';
915
+ a_default_partition TEXT := pgmq.format_table_name(queue_name, 'a'::pg_catalog.text) || '_default';
916
+ default_partition_length BIGINT;
917
+ BEGIN
918
+ -- Only partitioned queues have default partitions. Messages in them have no
919
+ -- partition of their own, which means pg_partman maintenance is failing for
920
+ -- this queue; a non-zero value here is the signal to act on. The planner's
921
+ -- estimate is used so that a large spill does not slow down every scrape.
922
+ IF to_regclass(FORMAT('pgmq.%I', q_default_partition)) IS NOT NULL THEN
923
+ SELECT COALESCE(SUM(GREATEST(c.reltuples, 0))::bigint, 0)
924
+ INTO default_partition_length
925
+ FROM pg_class c
926
+ WHERE c.oid IN (
927
+ to_regclass(FORMAT('pgmq.%I', q_default_partition)),
928
+ to_regclass(FORMAT('pgmq.%I', a_default_partition))
929
+ );
930
+ END IF;
931
+
932
+ query := FORMAT(
933
+ $QUERY$
934
+ WITH q_summary AS (
935
+ SELECT
936
+ count(*) as queue_length,
937
+ count(CASE WHEN vt <= NOW() THEN 1 END) as queue_visible_length,
938
+ EXTRACT(epoch FROM (NOW() - max(enqueued_at)))::int as newest_msg_age_sec,
939
+ EXTRACT(epoch FROM (NOW() - min(enqueued_at)))::int as oldest_msg_age_sec,
940
+ NOW() as scrape_time
941
+ FROM pgmq.%I
942
+ ),
943
+ all_metrics AS (
944
+ SELECT CASE
945
+ WHEN is_called THEN last_value ELSE 0
946
+ END as total_messages
947
+ FROM pgmq.%I
948
+ )
949
+ SELECT
950
+ %L as queue_name,
951
+ q_summary.queue_length,
952
+ q_summary.newest_msg_age_sec,
953
+ q_summary.oldest_msg_age_sec,
954
+ all_metrics.total_messages,
955
+ q_summary.scrape_time,
956
+ q_summary.queue_visible_length,
957
+ %L::bigint as default_partition_length
958
+ FROM q_summary, all_metrics
959
+ $QUERY$,
960
+ qtable, qtable || '_msg_id_seq', queue_name, default_partition_length
961
+ );
962
+ EXECUTE query INTO result_row;
963
+ RETURN result_row;
964
+ END;
965
+ $$ LANGUAGE plpgsql SET search_path = pg_catalog, pg_temp;
966
+
967
+ -- get metrics for all queues
968
+ CREATE FUNCTION pgmq."metrics_all"()
969
+ RETURNS SETOF pgmq.metrics_result AS $$
970
+ DECLARE
971
+ row_name RECORD;
972
+ result_row pgmq.metrics_result;
973
+ BEGIN
974
+ FOR row_name IN SELECT queue_name FROM pgmq.meta LOOP
975
+ result_row := pgmq.metrics(row_name.queue_name::pg_catalog.text);
976
+ RETURN NEXT result_row;
977
+ END LOOP;
978
+ END;
979
+ $$ LANGUAGE plpgsql SET search_path = pg_catalog, pg_temp;
980
+
981
+ -- list queues
982
+ CREATE FUNCTION pgmq."list_queues"()
983
+ RETURNS SETOF pgmq.queue_record AS $$
984
+ BEGIN
985
+ RETURN QUERY SELECT * FROM pgmq.meta;
986
+ END
987
+ $$ LANGUAGE plpgsql SET search_path = pg_catalog, pg_temp;
988
+
989
+ -- purge queue, deleting all entries in it.
990
+ CREATE OR REPLACE FUNCTION pgmq."purge_queue"(queue_name TEXT)
991
+ RETURNS BIGINT AS $$
992
+ DECLARE
993
+ deleted_count INTEGER;
994
+ qtable TEXT := pgmq.format_table_name(queue_name, 'q'::pg_catalog.text);
995
+ BEGIN
996
+ -- Get the row count before truncating
997
+ EXECUTE format('SELECT count(*) FROM pgmq.%I', qtable) INTO deleted_count;
998
+
999
+ -- Use TRUNCATE for better performance on large tables
1000
+ EXECUTE format('TRUNCATE TABLE pgmq.%I', qtable);
1001
+
1002
+ -- Return the number of purged rows
1003
+ RETURN deleted_count;
1004
+ END
1005
+ $$ LANGUAGE plpgsql SET search_path = pg_catalog, pg_temp;
1006
+
1007
+ -- unassign archive, so it can be kept when a queue is deleted
1008
+ CREATE FUNCTION pgmq."detach_archive"(queue_name TEXT)
1009
+ RETURNS VOID AS $$
1010
+ DECLARE
1011
+ atable TEXT := pgmq.format_table_name(queue_name, 'a'::pg_catalog.text);
1012
+ BEGIN
1013
+ RAISE WARNING 'detach_archive(queue_name) is deprecated and is a no-op. It will be removed in PGMQ v2.0. Archive tables are no longer member objects.';
1014
+ END
1015
+ $$ LANGUAGE plpgsql SET search_path = pg_catalog, pg_temp;
1016
+
1017
+ -- pop: implementation
1018
+ CREATE FUNCTION pgmq.pop(queue_name TEXT, qty INTEGER DEFAULT 1)
1019
+ RETURNS SETOF pgmq.message_record AS $$
1020
+ DECLARE
1021
+ sql TEXT;
1022
+ result pgmq.message_record;
1023
+ qtable TEXT := pgmq.format_table_name(queue_name, 'q'::pg_catalog.text);
1024
+ BEGIN
1025
+ sql := FORMAT(
1026
+ $QUERY$
1027
+ WITH cte AS
1028
+ (
1029
+ SELECT msg_id
1030
+ FROM pgmq.%I
1031
+ WHERE vt <= clock_timestamp()
1032
+ ORDER BY msg_id ASC
1033
+ LIMIT $1
1034
+ FOR UPDATE SKIP LOCKED
1035
+ )
1036
+ DELETE from pgmq.%I
1037
+ WHERE msg_id IN (select msg_id from cte)
1038
+ RETURNING msg_id, read_ct, enqueued_at, last_read_at, vt, message, headers;
1039
+ $QUERY$,
1040
+ qtable, qtable
1041
+ );
1042
+ RETURN QUERY EXECUTE sql USING qty;
1043
+ END;
1044
+ $$ LANGUAGE plpgsql SET search_path = pg_catalog, pg_temp;
1045
+
1046
+ -- Sets timestamp vt of a message, returns it
1047
+ CREATE FUNCTION pgmq.set_vt(queue_name TEXT, msg_id BIGINT, vt TIMESTAMP WITH TIME ZONE)
1048
+ RETURNS SETOF pgmq.message_record AS $$
1049
+ DECLARE
1050
+ sql TEXT;
1051
+ result pgmq.message_record;
1052
+ qtable TEXT := pgmq.format_table_name(queue_name, 'q'::pg_catalog.text);
1053
+ BEGIN
1054
+ sql := FORMAT(
1055
+ $QUERY$
1056
+ UPDATE pgmq.%I
1057
+ SET vt = $1
1058
+ WHERE msg_id = $2
1059
+ RETURNING msg_id, read_ct, enqueued_at, last_read_at, vt, message, headers;
1060
+ $QUERY$,
1061
+ qtable
1062
+ );
1063
+ RETURN QUERY EXECUTE sql USING vt, msg_id;
1064
+ END;
1065
+ $$ LANGUAGE plpgsql SET search_path = pg_catalog, pg_temp;
1066
+
1067
+ -- Sets integer vt of a message, returns it
1068
+ CREATE FUNCTION pgmq.set_vt(queue_name TEXT, msg_id BIGINT, vt INTEGER)
1069
+ RETURNS SETOF pgmq.message_record AS $$
1070
+ SELECT * FROM pgmq.set_vt(queue_name, msg_id, clock_timestamp() + pg_catalog.make_interval(secs => vt));
1071
+ $$ LANGUAGE sql SET search_path = pg_catalog, pg_temp;
1072
+
1073
+ -- Sets timestamp vt of multiple messages, returns them
1074
+ CREATE FUNCTION pgmq.set_vt(
1075
+ queue_name TEXT,
1076
+ msg_ids BIGINT[],
1077
+ vt TIMESTAMP WITH TIME ZONE
1078
+ )
1079
+ RETURNS SETOF pgmq.message_record AS $$
1080
+ DECLARE
1081
+ sql TEXT;
1082
+ qtable TEXT := pgmq.format_table_name(queue_name, 'q'::pg_catalog.text);
1083
+ BEGIN
1084
+ sql := FORMAT(
1085
+ $QUERY$
1086
+ UPDATE pgmq.%I
1087
+ SET vt = $1
1088
+ WHERE msg_id = ANY($2)
1089
+ RETURNING msg_id, read_ct, enqueued_at, last_read_at, vt, message, headers;
1090
+ $QUERY$,
1091
+ qtable
1092
+ );
1093
+ RETURN QUERY EXECUTE sql USING vt, msg_ids;
1094
+ END;
1095
+ $$ LANGUAGE plpgsql SET search_path = pg_catalog, pg_temp;
1096
+
1097
+ -- Sets integer vt of multiple messages, returns them
1098
+ CREATE FUNCTION pgmq.set_vt(
1099
+ queue_name TEXT,
1100
+ msg_ids BIGINT[],
1101
+ vt INTEGER
1102
+ )
1103
+ RETURNS SETOF pgmq.message_record AS $$
1104
+ SELECT * FROM pgmq.set_vt(queue_name, msg_ids, clock_timestamp() + pg_catalog.make_interval(secs => vt));
1105
+ $$ LANGUAGE sql SET search_path = pg_catalog, pg_temp;
1106
+
1107
+ CREATE FUNCTION pgmq._get_pg_partman_schema()
1108
+ RETURNS TEXT AS $$
1109
+ SELECT
1110
+ extnamespace::regnamespace::text
1111
+ FROM
1112
+ pg_extension
1113
+ WHERE
1114
+ extname = 'pg_partman';
1115
+ $$ LANGUAGE SQL SET search_path = pg_catalog, pg_temp;
1116
+
1117
+ CREATE FUNCTION pgmq.drop_queue(queue_name TEXT, partitioned BOOLEAN)
1118
+ RETURNS BOOLEAN AS $$
1119
+ DECLARE
1120
+ qtable TEXT := pgmq.format_table_name(queue_name, 'q'::pg_catalog.text);
1121
+ fq_qtable TEXT := 'pgmq.' || qtable;
1122
+ atable TEXT := pgmq.format_table_name(queue_name, 'a'::pg_catalog.text);
1123
+ fq_atable TEXT := 'pgmq.' || atable;
1124
+ BEGIN
1125
+ RAISE WARNING 'drop_queue(queue_name, partitioned) is deprecated and will be removed in PGMQ v2.0. Use drop_queue(queue_name) instead';
1126
+
1127
+ PERFORM pgmq.drop_queue(queue_name);
1128
+
1129
+ RETURN TRUE;
1130
+ END;
1131
+ $$ LANGUAGE plpgsql SET search_path = pg_catalog, pg_temp;
1132
+
1133
+ CREATE FUNCTION pgmq.drop_queue(queue_name TEXT)
1134
+ RETURNS BOOLEAN AS $$
1135
+ DECLARE
1136
+ qtable TEXT := pgmq.format_table_name(queue_name, 'q'::pg_catalog.text);
1137
+ qtable_seq TEXT := qtable || '_msg_id_seq';
1138
+ fq_qtable TEXT := 'pgmq.' || qtable;
1139
+ atable TEXT := pgmq.format_table_name(queue_name, 'a'::pg_catalog.text);
1140
+ fq_atable TEXT := 'pgmq.' || atable;
1141
+ partitioned BOOLEAN;
1142
+ BEGIN
1143
+ PERFORM pgmq.acquire_queue_lock(queue_name);
1144
+ EXECUTE FORMAT(
1145
+ $QUERY$
1146
+ SELECT is_partitioned FROM pgmq.meta WHERE queue_name = %L
1147
+ $QUERY$,
1148
+ queue_name
1149
+ ) INTO partitioned;
1150
+
1151
+ -- check if the queue exists
1152
+ IF NOT EXISTS (
1153
+ SELECT 1
1154
+ FROM information_schema.tables
1155
+ WHERE table_name = qtable and table_schema = 'pgmq'
1156
+ ) THEN
1157
+ RAISE NOTICE 'pgmq queue `%` does not exist', queue_name;
1158
+ RETURN FALSE;
1159
+ END IF;
1160
+
1161
+ EXECUTE FORMAT(
1162
+ $QUERY$
1163
+ DROP TABLE IF EXISTS pgmq.%I
1164
+ $QUERY$,
1165
+ qtable
1166
+ );
1167
+
1168
+ EXECUTE FORMAT(
1169
+ $QUERY$
1170
+ DROP TABLE IF EXISTS pgmq.%I
1171
+ $QUERY$,
1172
+ atable
1173
+ );
1174
+
1175
+ IF EXISTS (
1176
+ SELECT 1
1177
+ FROM information_schema.tables
1178
+ WHERE table_name = 'meta' and table_schema = 'pgmq'
1179
+ ) THEN
1180
+ EXECUTE FORMAT(
1181
+ $QUERY$
1182
+ DELETE FROM pgmq.meta WHERE queue_name = %L
1183
+ $QUERY$,
1184
+ queue_name
1185
+ );
1186
+ END IF;
1187
+
1188
+ IF partitioned THEN
1189
+ EXECUTE FORMAT(
1190
+ $QUERY$
1191
+ DELETE FROM %I.part_config where parent_table in (%L, %L)
1192
+ $QUERY$,
1193
+ pgmq._get_pg_partman_schema(), fq_qtable, fq_atable
1194
+ );
1195
+ END IF;
1196
+
1197
+ RETURN TRUE;
1198
+ END;
1199
+ $$ LANGUAGE plpgsql SET search_path = pg_catalog, pg_temp;
1200
+
1201
+ CREATE FUNCTION pgmq.validate_queue_name(queue_name TEXT)
1202
+ RETURNS void AS $$
1203
+ BEGIN
1204
+ IF length(queue_name) > 47 THEN
1205
+ -- complete table identifier must be <= 63
1206
+ -- https://www.postgresql.org/docs/17/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS
1207
+ -- e.g. template_pgmq_q_my_queue is an identifier for my_queue when partitioned
1208
+ -- template_pgmq_q_ (16) + <a max length queue name> (47) = 63
1209
+ RAISE EXCEPTION 'queue name is too long, maximum length is 47 characters';
1210
+ END IF;
1211
+ END;
1212
+ $$ LANGUAGE plpgsql SET search_path = pg_catalog, pg_temp;
1213
+
1214
+ CREATE FUNCTION pgmq._belongs_to_pgmq(table_name TEXT)
1215
+ RETURNS BOOLEAN AS $$
1216
+ DECLARE
1217
+ sql TEXT;
1218
+ result BOOLEAN;
1219
+ BEGIN
1220
+ SELECT EXISTS (
1221
+ SELECT 1
1222
+ FROM pg_depend
1223
+ WHERE refobjid = (SELECT oid FROM pg_extension WHERE extname = 'pgmq')
1224
+ AND objid = (
1225
+ SELECT oid
1226
+ FROM pg_class
1227
+ WHERE relname = table_name
1228
+ )
1229
+ ) INTO result;
1230
+ RETURN result;
1231
+ END;
1232
+ $$ LANGUAGE plpgsql SET search_path = pg_catalog, pg_temp;
1233
+
1234
+ CREATE FUNCTION pgmq.create_non_partitioned(queue_name TEXT)
1235
+ RETURNS void AS $$
1236
+ DECLARE
1237
+ qtable TEXT := pgmq.format_table_name(queue_name, 'q'::pg_catalog.text);
1238
+ qtable_seq TEXT := qtable || '_msg_id_seq';
1239
+ atable TEXT := pgmq.format_table_name(queue_name, 'a'::pg_catalog.text);
1240
+ BEGIN
1241
+ PERFORM pgmq.validate_queue_name(queue_name);
1242
+ PERFORM pgmq.acquire_queue_lock(queue_name);
1243
+
1244
+ EXECUTE FORMAT(
1245
+ $QUERY$
1246
+ CREATE TABLE IF NOT EXISTS pgmq.%I (
1247
+ msg_id BIGINT PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
1248
+ read_ct INT DEFAULT 0 NOT NULL,
1249
+ enqueued_at TIMESTAMP WITH TIME ZONE DEFAULT now() NOT NULL,
1250
+ last_read_at TIMESTAMP WITH TIME ZONE,
1251
+ vt TIMESTAMP WITH TIME ZONE NOT NULL,
1252
+ message JSONB,
1253
+ headers JSONB
1254
+ )
1255
+ $QUERY$,
1256
+ qtable
1257
+ );
1258
+
1259
+ EXECUTE FORMAT(
1260
+ $QUERY$
1261
+ CREATE TABLE IF NOT EXISTS pgmq.%I (
1262
+ msg_id BIGINT PRIMARY KEY,
1263
+ read_ct INT DEFAULT 0 NOT NULL,
1264
+ enqueued_at TIMESTAMP WITH TIME ZONE DEFAULT now() NOT NULL,
1265
+ last_read_at TIMESTAMP WITH TIME ZONE,
1266
+ archived_at TIMESTAMP WITH TIME ZONE DEFAULT now() NOT NULL,
1267
+ vt TIMESTAMP WITH TIME ZONE NOT NULL,
1268
+ message JSONB,
1269
+ headers JSONB
1270
+ );
1271
+ $QUERY$,
1272
+ atable
1273
+ );
1274
+
1275
+ -- CREATE INDEX takes a SHARE lock on the table before it checks IF NOT EXISTS, so on an existing queue it
1276
+ -- would wait for every open transaction that has written to it. to_regclass() takes no lock: only run the
1277
+ -- DDL when the index is actually missing, which keeps create() idempotent (it still repairs a missing index).
1278
+ IF to_regclass(FORMAT('pgmq.%I', qtable || '_vt_idx')) IS NULL THEN
1279
+ EXECUTE FORMAT(
1280
+ $QUERY$
1281
+ CREATE INDEX IF NOT EXISTS %I ON pgmq.%I (vt ASC);
1282
+ $QUERY$,
1283
+ qtable || '_vt_idx', qtable
1284
+ );
1285
+ END IF;
1286
+
1287
+ IF to_regclass(FORMAT('pgmq.%I', 'archived_at_idx_' || queue_name)) IS NULL THEN
1288
+ EXECUTE FORMAT(
1289
+ $QUERY$
1290
+ CREATE INDEX IF NOT EXISTS %I ON pgmq.%I (archived_at);
1291
+ $QUERY$,
1292
+ 'archived_at_idx_' || queue_name, atable
1293
+ );
1294
+ END IF;
1295
+
1296
+ EXECUTE FORMAT(
1297
+ $QUERY$
1298
+ INSERT INTO pgmq.meta (queue_name, is_partitioned, is_unlogged)
1299
+ VALUES (%L, false, false)
1300
+ ON CONFLICT
1301
+ DO NOTHING;
1302
+ $QUERY$,
1303
+ queue_name
1304
+ );
1305
+
1306
+ -- Let pg_monitor compute queue metrics (pgmq.metrics / pgmq.metrics_all) without exposing
1307
+ -- message payloads: column-level SELECT on the metrics columns only, plus the msg_id sequence.
1308
+ -- Skip the grants when pg_monitor already has them, so a create() on an existing queue doesn't rewrite catalog rows.
1309
+ IF NOT (
1310
+ has_column_privilege('pg_monitor', FORMAT('pgmq.%I', qtable), 'vt', 'SELECT')
1311
+ AND has_column_privilege('pg_monitor', FORMAT('pgmq.%I', qtable), 'enqueued_at', 'SELECT')
1312
+ ) THEN
1313
+ EXECUTE FORMAT('GRANT SELECT (vt, enqueued_at) ON pgmq.%I TO pg_monitor', qtable);
1314
+ END IF;
1315
+ IF NOT has_sequence_privilege('pg_monitor', FORMAT('pgmq.%I', qtable_seq), 'SELECT') THEN
1316
+ EXECUTE FORMAT('GRANT SELECT ON SEQUENCE pgmq.%I TO pg_monitor', qtable_seq);
1317
+ END IF;
1318
+
1319
+ END;
1320
+ $$ LANGUAGE plpgsql SET search_path = pg_catalog, pg_temp;
1321
+
1322
+ CREATE FUNCTION pgmq.create_unlogged(queue_name TEXT)
1323
+ RETURNS void AS $$
1324
+ DECLARE
1325
+ qtable TEXT := pgmq.format_table_name(queue_name, 'q'::pg_catalog.text);
1326
+ qtable_seq TEXT := qtable || '_msg_id_seq';
1327
+ atable TEXT := pgmq.format_table_name(queue_name, 'a'::pg_catalog.text);
1328
+ BEGIN
1329
+ PERFORM pgmq.validate_queue_name(queue_name);
1330
+ PERFORM pgmq.acquire_queue_lock(queue_name);
1331
+
1332
+ EXECUTE FORMAT(
1333
+ $QUERY$
1334
+ CREATE UNLOGGED TABLE IF NOT EXISTS pgmq.%I (
1335
+ msg_id BIGINT PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
1336
+ read_ct INT DEFAULT 0 NOT NULL,
1337
+ enqueued_at TIMESTAMP WITH TIME ZONE DEFAULT now() NOT NULL,
1338
+ last_read_at TIMESTAMP WITH TIME ZONE,
1339
+ vt TIMESTAMP WITH TIME ZONE NOT NULL,
1340
+ message JSONB,
1341
+ headers JSONB
1342
+ )
1343
+ $QUERY$,
1344
+ qtable
1345
+ );
1346
+
1347
+ EXECUTE FORMAT(
1348
+ $QUERY$
1349
+ CREATE TABLE IF NOT EXISTS pgmq.%I (
1350
+ msg_id BIGINT PRIMARY KEY,
1351
+ read_ct INT DEFAULT 0 NOT NULL,
1352
+ enqueued_at TIMESTAMP WITH TIME ZONE DEFAULT now() NOT NULL,
1353
+ last_read_at TIMESTAMP WITH TIME ZONE,
1354
+ archived_at TIMESTAMP WITH TIME ZONE DEFAULT now() NOT NULL,
1355
+ vt TIMESTAMP WITH TIME ZONE NOT NULL,
1356
+ message JSONB,
1357
+ headers JSONB
1358
+ );
1359
+ $QUERY$,
1360
+ atable
1361
+ );
1362
+
1363
+ -- CREATE INDEX takes a SHARE lock on the table before it checks IF NOT EXISTS, so on an existing queue it
1364
+ -- would wait for every open transaction that has written to it. to_regclass() takes no lock: only run the
1365
+ -- DDL when the index is actually missing, which keeps create() idempotent (it still repairs a missing index).
1366
+ IF to_regclass(FORMAT('pgmq.%I', qtable || '_vt_idx')) IS NULL THEN
1367
+ EXECUTE FORMAT(
1368
+ $QUERY$
1369
+ CREATE INDEX IF NOT EXISTS %I ON pgmq.%I (vt ASC);
1370
+ $QUERY$,
1371
+ qtable || '_vt_idx', qtable
1372
+ );
1373
+ END IF;
1374
+
1375
+ IF to_regclass(FORMAT('pgmq.%I', 'archived_at_idx_' || queue_name)) IS NULL THEN
1376
+ EXECUTE FORMAT(
1377
+ $QUERY$
1378
+ CREATE INDEX IF NOT EXISTS %I ON pgmq.%I (archived_at);
1379
+ $QUERY$,
1380
+ 'archived_at_idx_' || queue_name, atable
1381
+ );
1382
+ END IF;
1383
+
1384
+ EXECUTE FORMAT(
1385
+ $QUERY$
1386
+ INSERT INTO pgmq.meta (queue_name, is_partitioned, is_unlogged)
1387
+ VALUES (%L, false, true)
1388
+ ON CONFLICT
1389
+ DO NOTHING;
1390
+ $QUERY$,
1391
+ queue_name
1392
+ );
1393
+
1394
+ -- Let pg_monitor compute queue metrics (pgmq.metrics / pgmq.metrics_all) without exposing
1395
+ -- message payloads: column-level SELECT on the metrics columns only, plus the msg_id sequence.
1396
+ -- Skip the grants when pg_monitor already has them, so a create() on an existing queue doesn't rewrite catalog rows.
1397
+ IF NOT (
1398
+ has_column_privilege('pg_monitor', FORMAT('pgmq.%I', qtable), 'vt', 'SELECT')
1399
+ AND has_column_privilege('pg_monitor', FORMAT('pgmq.%I', qtable), 'enqueued_at', 'SELECT')
1400
+ ) THEN
1401
+ EXECUTE FORMAT('GRANT SELECT (vt, enqueued_at) ON pgmq.%I TO pg_monitor', qtable);
1402
+ END IF;
1403
+ IF NOT has_sequence_privilege('pg_monitor', FORMAT('pgmq.%I', qtable_seq), 'SELECT') THEN
1404
+ EXECUTE FORMAT('GRANT SELECT ON SEQUENCE pgmq.%I TO pg_monitor', qtable_seq);
1405
+ END IF;
1406
+ END;
1407
+ $$ LANGUAGE plpgsql SET search_path = pg_catalog, pg_temp;
1408
+
1409
+ CREATE FUNCTION pgmq._get_partition_col(partition_interval TEXT)
1410
+ RETURNS TEXT AS $$
1411
+ DECLARE
1412
+ num INTEGER;
1413
+ BEGIN
1414
+ BEGIN
1415
+ num := partition_interval::INTEGER;
1416
+ RETURN 'msg_id';
1417
+ EXCEPTION
1418
+ WHEN others THEN
1419
+ RETURN 'enqueued_at';
1420
+ END;
1421
+ END;
1422
+ $$ LANGUAGE plpgsql SET search_path = pg_catalog, pg_temp;
1423
+
1424
+ CREATE FUNCTION pgmq._extension_exists(extension_name TEXT)
1425
+ RETURNS BOOLEAN
1426
+ LANGUAGE SQL
1427
+ SET search_path = pg_catalog, pg_temp
1428
+ AS $$
1429
+ SELECT EXISTS (
1430
+ SELECT 1
1431
+ FROM pg_extension
1432
+ WHERE extname = extension_name
1433
+ )
1434
+ $$;
1435
+
1436
+ CREATE FUNCTION pgmq._ensure_pg_partman_installed()
1437
+ RETURNS void AS $$
1438
+ BEGIN
1439
+ IF NOT pgmq._extension_exists('pg_partman'::pg_catalog.text) THEN
1440
+ RAISE EXCEPTION 'pg_partman is required for partitioned queues';
1441
+ END IF;
1442
+ END;
1443
+ $$ LANGUAGE plpgsql SET search_path = pg_catalog, pg_temp;
1444
+
1445
+ CREATE FUNCTION pgmq._get_pg_partman_major_version()
1446
+ RETURNS INT
1447
+ LANGUAGE SQL
1448
+ SET search_path = pg_catalog, pg_temp
1449
+ AS $$
1450
+ SELECT split_part(extversion, '.', 1)::INT
1451
+ FROM pg_extension
1452
+ WHERE extname = 'pg_partman'
1453
+ $$;
1454
+
1455
+ -- pg_partman.create_parent uses set_config(..., false). Keep its side effect
1456
+ -- inside the implementation, then restore the caller's path in the wrapper.
1457
+ CREATE FUNCTION pgmq._create_partitioned(
1458
+ queue_name TEXT,
1459
+ partition_interval TEXT,
1460
+ retention_interval TEXT,
1461
+ premake INTEGER
1462
+ )
1463
+ RETURNS void AS $$
1464
+ DECLARE
1465
+ partition_col TEXT;
1466
+ a_partition_col TEXT;
1467
+ qtable TEXT := pgmq.format_table_name(queue_name, 'q'::pg_catalog.text);
1468
+ qtable_seq TEXT := qtable || '_msg_id_seq';
1469
+ atable TEXT := pgmq.format_table_name(queue_name, 'a'::pg_catalog.text);
1470
+ fq_qtable TEXT := 'pgmq.' || qtable;
1471
+ fq_atable TEXT := 'pgmq.' || atable;
1472
+ BEGIN
1473
+ PERFORM pgmq.validate_queue_name(queue_name);
1474
+ PERFORM pgmq.acquire_queue_lock(queue_name);
1475
+ PERFORM pgmq._ensure_pg_partman_installed();
1476
+ IF premake < 1 THEN
1477
+ RAISE EXCEPTION 'premake must be at least 1, got %', premake;
1478
+ END IF;
1479
+ SELECT pgmq._get_partition_col(partition_interval) INTO partition_col;
1480
+
1481
+ EXECUTE FORMAT(
1482
+ $QUERY$
1483
+ CREATE TABLE IF NOT EXISTS pgmq.%I (
1484
+ msg_id BIGINT GENERATED BY DEFAULT AS IDENTITY,
1485
+ read_ct INT DEFAULT 0 NOT NULL,
1486
+ enqueued_at TIMESTAMP WITH TIME ZONE DEFAULT now() NOT NULL,
1487
+ last_read_at TIMESTAMP WITH TIME ZONE,
1488
+ vt TIMESTAMP WITH TIME ZONE NOT NULL,
1489
+ message JSONB,
1490
+ headers JSONB
1491
+ ) PARTITION BY RANGE (%I)
1492
+ $QUERY$,
1493
+ qtable, partition_col
1494
+ );
1495
+
1496
+ -- https://github.com/pgpartman/pg_partman/blob/master/doc/pg_partman.md
1497
+ -- p_parent_table - the existing parent table. MUST be schema qualified, even if in public schema.
1498
+ EXECUTE FORMAT(
1499
+ $QUERY$
1500
+ SELECT %I.create_parent(
1501
+ p_parent_table := %L,
1502
+ p_control := %L,
1503
+ p_interval := %L,
1504
+ p_premake := %s,
1505
+ p_type := case
1506
+ when pgmq._get_pg_partman_major_version() = 5 then 'range'
1507
+ else 'native'
1508
+ end
1509
+ )
1510
+ $QUERY$,
1511
+ pgmq._get_pg_partman_schema(),
1512
+ fq_qtable,
1513
+ partition_col,
1514
+ partition_interval,
1515
+ premake
1516
+ );
1517
+
1518
+ EXECUTE FORMAT(
1519
+ $QUERY$
1520
+ CREATE INDEX IF NOT EXISTS %I ON pgmq.%I (%I);
1521
+ $QUERY$,
1522
+ qtable || '_part_idx', qtable, partition_col
1523
+ );
1524
+
1525
+ EXECUTE FORMAT(
1526
+ $QUERY$
1527
+ UPDATE %I.part_config
1528
+ SET
1529
+ retention = %L,
1530
+ retention_keep_table = false,
1531
+ retention_keep_index = true,
1532
+ automatic_maintenance = 'on'
1533
+ WHERE parent_table = %L;
1534
+ $QUERY$,
1535
+ pgmq._get_pg_partman_schema(),
1536
+ retention_interval,
1537
+ 'pgmq.' || qtable
1538
+ );
1539
+
1540
+ EXECUTE FORMAT(
1541
+ $QUERY$
1542
+ INSERT INTO pgmq.meta (queue_name, is_partitioned, is_unlogged)
1543
+ VALUES (%L, true, false)
1544
+ ON CONFLICT
1545
+ DO NOTHING;
1546
+ $QUERY$,
1547
+ queue_name
1548
+ );
1549
+
1550
+ IF partition_col = 'enqueued_at' THEN
1551
+ a_partition_col := 'archived_at';
1552
+ ELSE
1553
+ a_partition_col := partition_col;
1554
+ END IF;
1555
+
1556
+ EXECUTE FORMAT(
1557
+ $QUERY$
1558
+ CREATE TABLE IF NOT EXISTS pgmq.%I (
1559
+ msg_id BIGINT NOT NULL,
1560
+ read_ct INT DEFAULT 0 NOT NULL,
1561
+ enqueued_at TIMESTAMP WITH TIME ZONE DEFAULT now() NOT NULL,
1562
+ last_read_at TIMESTAMP WITH TIME ZONE,
1563
+ archived_at TIMESTAMP WITH TIME ZONE DEFAULT now() NOT NULL,
1564
+ vt TIMESTAMP WITH TIME ZONE NOT NULL,
1565
+ message JSONB,
1566
+ headers JSONB
1567
+ ) PARTITION BY RANGE (%I);
1568
+ $QUERY$,
1569
+ atable, a_partition_col
1570
+ );
1571
+
1572
+ -- https://github.com/pgpartman/pg_partman/blob/master/doc/pg_partman.md
1573
+ -- p_parent_table - the existing parent table. MUST be schema qualified, even if in public schema.
1574
+ EXECUTE FORMAT(
1575
+ $QUERY$
1576
+ SELECT %I.create_parent(
1577
+ p_parent_table := %L,
1578
+ p_control := %L,
1579
+ p_interval := %L,
1580
+ p_premake := %s,
1581
+ p_type := case
1582
+ when pgmq._get_pg_partman_major_version() = 5 then 'range'
1583
+ else 'native'
1584
+ end
1585
+ )
1586
+ $QUERY$,
1587
+ pgmq._get_pg_partman_schema(),
1588
+ fq_atable,
1589
+ a_partition_col,
1590
+ partition_interval,
1591
+ premake
1592
+ );
1593
+
1594
+ EXECUTE FORMAT(
1595
+ $QUERY$
1596
+ UPDATE %I.part_config
1597
+ SET
1598
+ retention = %L,
1599
+ retention_keep_table = false,
1600
+ retention_keep_index = true,
1601
+ automatic_maintenance = 'on'
1602
+ WHERE parent_table = %L;
1603
+ $QUERY$,
1604
+ pgmq._get_pg_partman_schema(),
1605
+ retention_interval,
1606
+ 'pgmq.' || atable
1607
+ );
1608
+
1609
+ EXECUTE FORMAT(
1610
+ $QUERY$
1611
+ CREATE INDEX IF NOT EXISTS %I ON pgmq.%I (archived_at);
1612
+ $QUERY$,
1613
+ 'archived_at_idx_' || queue_name, atable
1614
+ );
1615
+
1616
+ -- Let pg_monitor compute queue metrics (pgmq.metrics / pgmq.metrics_all) without exposing
1617
+ -- message payloads: column-level SELECT on the metrics columns only, plus the msg_id sequence.
1618
+ -- For partitioned queues, granting on the parent is sufficient: metrics query the parent and
1619
+ -- the privilege check is performed there, not on individual partitions.
1620
+ EXECUTE FORMAT('GRANT SELECT (vt, enqueued_at) ON pgmq.%I TO pg_monitor', qtable);
1621
+ EXECUTE FORMAT('GRANT SELECT ON SEQUENCE pgmq.%I TO pg_monitor', qtable_seq);
1622
+
1623
+ END;
1624
+ $$ LANGUAGE plpgsql SET search_path = pg_catalog, pg_temp;
1625
+
1626
+ CREATE FUNCTION pgmq.create_partitioned(
1627
+ queue_name TEXT,
1628
+ partition_interval TEXT DEFAULT '10000',
1629
+ retention_interval TEXT DEFAULT '100000',
1630
+ premake INTEGER DEFAULT 4
1631
+ )
1632
+ RETURNS void AS $$
1633
+ DECLARE
1634
+ caller_path pg_catalog.text := pg_catalog.current_setting('search_path');
1635
+ BEGIN
1636
+ PERFORM pgmq._create_partitioned(queue_name, partition_interval, retention_interval, premake);
1637
+ IF NOT (pg_catalog.current_setting('search_path') OPERATOR(pg_catalog.=) caller_path) THEN
1638
+ PERFORM pg_catalog.set_config('search_path', caller_path, false);
1639
+ END IF;
1640
+ END;
1641
+ $$ LANGUAGE plpgsql;
1642
+
1643
+ CREATE FUNCTION pgmq.create(queue_name TEXT)
1644
+ RETURNS void AS $$
1645
+ BEGIN
1646
+ PERFORM pgmq.create_non_partitioned(queue_name);
1647
+ END;
1648
+ $$ LANGUAGE plpgsql SET search_path = pg_catalog, pg_temp;
1649
+
1650
+ -- _create_fifo_index_if_not_exists
1651
+ -- internal function to create GIN index on headers for better FIFO performance
1652
+ CREATE OR REPLACE FUNCTION pgmq._create_fifo_index_if_not_exists(queue_name TEXT)
1653
+ RETURNS void AS $$
1654
+ DECLARE
1655
+ qtable TEXT := pgmq.format_table_name(queue_name, 'q'::pg_catalog.text);
1656
+ index_name TEXT := qtable || '_fifo_idx';
1657
+ BEGIN
1658
+ -- Create GIN index on headers for efficient FIFO key lookups
1659
+ EXECUTE FORMAT(
1660
+ $QUERY$
1661
+ CREATE INDEX IF NOT EXISTS %I ON pgmq.%I USING GIN (headers);
1662
+ $QUERY$,
1663
+ index_name, qtable
1664
+ );
1665
+ END;
1666
+ $$ LANGUAGE plpgsql SET search_path = pg_catalog, pg_temp;
1667
+
1668
+ -- create_fifo_index
1669
+ -- creates a GIN index on the headers column to improve FIFO read performance
1670
+ CREATE FUNCTION pgmq.create_fifo_index(queue_name TEXT)
1671
+ RETURNS void AS $$
1672
+ BEGIN
1673
+ PERFORM pgmq._create_fifo_index_if_not_exists(queue_name);
1674
+ END;
1675
+ $$ LANGUAGE plpgsql SET search_path = pg_catalog, pg_temp;
1676
+
1677
+ -- create_fifo_indexes_all
1678
+ -- creates FIFO indexes on all existing queues
1679
+ CREATE FUNCTION pgmq.create_fifo_indexes_all()
1680
+ RETURNS void AS $$
1681
+ DECLARE
1682
+ queue_record RECORD;
1683
+ BEGIN
1684
+ FOR queue_record IN SELECT queue_name FROM pgmq.meta LOOP
1685
+ PERFORM pgmq.create_fifo_index(queue_record.queue_name::pg_catalog.text);
1686
+ END LOOP;
1687
+ END;
1688
+ $$ LANGUAGE plpgsql SET search_path = pg_catalog, pg_temp;
1689
+
1690
+ CREATE OR REPLACE FUNCTION pgmq._convert_archive_partitioned(
1691
+ table_name TEXT,
1692
+ partition_interval TEXT,
1693
+ retention_interval TEXT,
1694
+ leading_partition INT
1695
+ )
1696
+ RETURNS void AS $$
1697
+ DECLARE
1698
+ a_table_name TEXT := pgmq.format_table_name(table_name, 'a'::pg_catalog.text);
1699
+ a_table_name_old TEXT := pgmq.format_table_name(table_name, 'a'::pg_catalog.text) || '_old';
1700
+ qualified_a_table_name TEXT := format('pgmq.%I', a_table_name);
1701
+ partition_col TEXT;
1702
+ a_partition_col TEXT;
1703
+ BEGIN
1704
+
1705
+ PERFORM c.relkind
1706
+ FROM pg_class c
1707
+ JOIN pg_namespace n ON n.oid = c.relnamespace
1708
+ WHERE c.relname = a_table_name
1709
+ AND c.relkind = 'p';
1710
+
1711
+ IF FOUND THEN
1712
+ RAISE NOTICE 'Table %s is already partitioned', a_table_name;
1713
+ RETURN;
1714
+ END IF;
1715
+
1716
+ PERFORM c.relkind
1717
+ FROM pg_class c
1718
+ JOIN pg_namespace n ON n.oid = c.relnamespace
1719
+ WHERE c.relname = a_table_name
1720
+ AND c.relkind = 'r';
1721
+
1722
+ IF NOT FOUND THEN
1723
+ RAISE NOTICE 'Table %s does not exists', a_table_name;
1724
+ RETURN;
1725
+ END IF;
1726
+
1727
+ SELECT pgmq._get_partition_col(partition_interval) INTO partition_col;
1728
+
1729
+ -- For archive tables, use archived_at for time-based partitioning
1730
+ IF partition_col = 'enqueued_at' THEN
1731
+ a_partition_col := 'archived_at';
1732
+ ELSE
1733
+ a_partition_col := partition_col;
1734
+ END IF;
1735
+
1736
+ EXECUTE 'ALTER TABLE ' || qualified_a_table_name || ' RENAME TO ' || a_table_name_old;
1737
+
1738
+ -- When partitioning by time (archived_at), we need to exclude constraints and indexes
1739
+ -- because the existing PRIMARY KEY on msg_id alone is incompatible with partitioning by archived_at.
1740
+ -- When partitioning by msg_id, we can keep all constraints including PRIMARY KEY.
1741
+ IF a_partition_col = 'archived_at' THEN
1742
+ EXECUTE format( 'CREATE TABLE pgmq.%I (LIKE pgmq.%I including defaults including generated including storage including comments) PARTITION BY RANGE (%I)', a_table_name, a_table_name_old, a_partition_col );
1743
+ ELSE
1744
+ EXECUTE format( 'CREATE TABLE pgmq.%I (LIKE pgmq.%I including all) PARTITION BY RANGE (%I)', a_table_name, a_table_name_old, a_partition_col );
1745
+ END IF;
1746
+
1747
+ EXECUTE 'ALTER INDEX pgmq.archived_at_idx_' || table_name || ' RENAME TO archived_at_idx_' || table_name || '_old';
1748
+ EXECUTE 'CREATE INDEX archived_at_idx_'|| table_name || ' ON ' || qualified_a_table_name ||'(archived_at)';
1749
+
1750
+ -- https://github.com/pgpartman/pg_partman/blob/master/doc/pg_partman.md
1751
+ -- p_parent_table - the existing parent table. MUST be schema qualified, even if in public schema.
1752
+ EXECUTE FORMAT(
1753
+ $QUERY$
1754
+ SELECT %I.create_parent(
1755
+ p_parent_table := %L,
1756
+ p_control := %L,
1757
+ p_interval := %L,
1758
+ p_type := case
1759
+ when pgmq._get_pg_partman_major_version() = 5 then 'range'
1760
+ else 'native'
1761
+ end
1762
+ )
1763
+ $QUERY$,
1764
+ pgmq._get_pg_partman_schema(),
1765
+ qualified_a_table_name,
1766
+ a_partition_col,
1767
+ partition_interval
1768
+ );
1769
+
1770
+ EXECUTE FORMAT(
1771
+ $QUERY$
1772
+ UPDATE %I.part_config
1773
+ SET
1774
+ retention = %L,
1775
+ retention_keep_table = false,
1776
+ retention_keep_index = false,
1777
+ infinite_time_partitions = true
1778
+ WHERE
1779
+ parent_table = %L;
1780
+ $QUERY$,
1781
+ pgmq._get_pg_partman_schema(),
1782
+ retention_interval,
1783
+ qualified_a_table_name
1784
+ );
1785
+ END;
1786
+ $$ LANGUAGE plpgsql SET search_path = pg_catalog, pg_temp;
1787
+
1788
+ CREATE OR REPLACE FUNCTION pgmq.convert_archive_partitioned(
1789
+ table_name TEXT,
1790
+ partition_interval TEXT DEFAULT '10000',
1791
+ retention_interval TEXT DEFAULT '100000',
1792
+ leading_partition INT DEFAULT 10
1793
+ )
1794
+ RETURNS void AS $$
1795
+ DECLARE
1796
+ caller_path pg_catalog.text := pg_catalog.current_setting('search_path');
1797
+ BEGIN
1798
+ PERFORM pgmq._convert_archive_partitioned(table_name, partition_interval, retention_interval, leading_partition);
1799
+ IF NOT (pg_catalog.current_setting('search_path') OPERATOR(pg_catalog.=) caller_path) THEN
1800
+ PERFORM pg_catalog.set_config('search_path', caller_path, false);
1801
+ END IF;
1802
+ END;
1803
+ $$ LANGUAGE plpgsql;
1804
+
1805
+ CREATE OR REPLACE FUNCTION pgmq.notify_queue_listeners()
1806
+ RETURNS TRIGGER AS $$
1807
+ DECLARE
1808
+ v_queue_name TEXT; -- Queue name, as stored in pgmq.meta
1809
+ updated_count INTEGER; -- Number of rows updated (0 or 1)
1810
+ BEGIN
1811
+ -- enable_notify_insert passes the queue name as a trigger argument. The table
1812
+ -- name cannot be turned back into it: format_table_name lowercases, so the
1813
+ -- queue MyQueue lives in pgmq.q_myqueue and stripping the prefix yields
1814
+ -- myqueue, which matches no row in notify_insert_throttle. Triggers created
1815
+ -- before the argument existed fall back to the table name.
1816
+ v_queue_name := COALESCE(TG_ARGV[0], substring(TG_TABLE_NAME from 3));
1817
+
1818
+ UPDATE pgmq.notify_insert_throttle
1819
+ SET last_notified_at = clock_timestamp()
1820
+ WHERE queue_name = v_queue_name
1821
+ AND (
1822
+ throttle_interval_ms = 0 -- No throttling configured
1823
+ OR clock_timestamp() - last_notified_at >=
1824
+ (throttle_interval_ms OPERATOR(pg_catalog.*) INTERVAL '1 millisecond') -- Throttle interval has elapsed
1825
+ );
1826
+
1827
+ -- Check how many rows were updated (will be 0 or 1)
1828
+ GET DIAGNOSTICS updated_count = ROW_COUNT;
1829
+
1830
+ IF updated_count > 0 THEN
1831
+ PERFORM PG_NOTIFY('pgmq.q_' || v_queue_name || '.' || TG_OP, NULL);
1832
+ END IF;
1833
+
1834
+ RETURN NEW;
1835
+ END;
1836
+ $$ LANGUAGE plpgsql SET search_path = pg_catalog, pg_temp;
1837
+
1838
+ CREATE OR REPLACE FUNCTION pgmq.enable_notify_insert(queue_name TEXT, throttle_interval_ms INTEGER DEFAULT 250)
1839
+ RETURNS void AS $$
1840
+ DECLARE
1841
+ qtable TEXT := pgmq.format_table_name(queue_name, 'q'::pg_catalog.text);
1842
+ v_queue_name TEXT := queue_name;
1843
+ v_throttle_interval_ms INTEGER := throttle_interval_ms;
1844
+ BEGIN
1845
+ -- Validate that throttle_interval_ms is non-negative
1846
+ IF v_throttle_interval_ms < 0 THEN
1847
+ RAISE EXCEPTION 'throttle_interval_ms must be non-negative';
1848
+ END IF;
1849
+
1850
+ -- Validate that the queue table exists
1851
+ IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'pgmq' AND table_name = qtable) THEN
1852
+ RAISE EXCEPTION 'Queue "%" does not exist. Create it first using pgmq.create()', v_queue_name;
1853
+ END IF;
1854
+
1855
+ PERFORM pgmq.disable_notify_insert(v_queue_name);
1856
+
1857
+ INSERT INTO pgmq.notify_insert_throttle (queue_name, throttle_interval_ms)
1858
+ VALUES (v_queue_name, v_throttle_interval_ms)
1859
+ ON CONFLICT ON CONSTRAINT notify_insert_throttle_queue_name_key DO UPDATE
1860
+ SET throttle_interval_ms = EXCLUDED.throttle_interval_ms,
1861
+ last_notified_at = pg_catalog.to_timestamp(0);
1862
+
1863
+ EXECUTE FORMAT(
1864
+ $QUERY$
1865
+ CREATE CONSTRAINT TRIGGER trigger_notify_queue_insert_listeners
1866
+ AFTER INSERT ON pgmq.%I
1867
+ DEFERRABLE FOR EACH ROW
1868
+ EXECUTE PROCEDURE pgmq.notify_queue_listeners(%L)
1869
+ $QUERY$,
1870
+ qtable, v_queue_name
1871
+ );
1872
+ END;
1873
+ $$ LANGUAGE plpgsql SET search_path = pg_catalog, pg_temp;
1874
+
1875
+ CREATE OR REPLACE FUNCTION pgmq.disable_notify_insert(queue_name TEXT)
1876
+ RETURNS void AS $$
1877
+ DECLARE
1878
+ qtable TEXT := pgmq.format_table_name(queue_name, 'q'::pg_catalog.text);
1879
+ v_queue_name TEXT := queue_name;
1880
+ BEGIN
1881
+ EXECUTE FORMAT(
1882
+ $QUERY$
1883
+ DROP TRIGGER IF EXISTS trigger_notify_queue_insert_listeners ON pgmq.%I;
1884
+ $QUERY$,
1885
+ qtable
1886
+ );
1887
+
1888
+ DELETE FROM pgmq.notify_insert_throttle nit WHERE nit.queue_name = v_queue_name;
1889
+ END;
1890
+ $$ LANGUAGE plpgsql SET search_path = pg_catalog, pg_temp;
1891
+
1892
+ CREATE OR REPLACE FUNCTION pgmq.list_notify_insert_throttles()
1893
+ RETURNS TABLE
1894
+ (
1895
+ queue_name text,
1896
+ throttle_interval_ms integer,
1897
+ last_notified_at TIMESTAMP WITH TIME ZONE
1898
+ )
1899
+ LANGUAGE sql
1900
+ STABLE
1901
+ SET search_path = pg_catalog, pg_temp
1902
+ AS
1903
+ $$
1904
+ SELECT queue_name, throttle_interval_ms, last_notified_at
1905
+ FROM pgmq.notify_insert_throttle
1906
+ ORDER BY queue_name;
1907
+ $$;
1908
+
1909
+ CREATE OR REPLACE FUNCTION pgmq.update_notify_insert(queue_name text, throttle_interval_ms integer)
1910
+ RETURNS void
1911
+ LANGUAGE plpgsql
1912
+ SET search_path = pg_catalog, pg_temp
1913
+ AS
1914
+ $$
1915
+ BEGIN
1916
+ IF throttle_interval_ms < 0 THEN
1917
+ RAISE EXCEPTION 'throttle_interval_ms must be non-negative, got: %', throttle_interval_ms;
1918
+ END IF;
1919
+
1920
+ IF NOT EXISTS (SELECT 1 FROM pgmq.meta WHERE meta.queue_name = update_notify_insert.queue_name) THEN
1921
+ RAISE EXCEPTION 'Queue "%" does not exist. Create the queue first using pgmq.create()', queue_name;
1922
+ END IF;
1923
+
1924
+ IF NOT EXISTS (SELECT 1 FROM pgmq.notify_insert_throttle WHERE notify_insert_throttle.queue_name = update_notify_insert.queue_name) THEN
1925
+ RAISE EXCEPTION 'Queue "%" does not have notify_insert enabled. Enable it first using pgmq.enable_notify_insert()', queue_name;
1926
+ END IF;
1927
+
1928
+ UPDATE pgmq.notify_insert_throttle
1929
+ SET throttle_interval_ms = update_notify_insert.throttle_interval_ms,
1930
+ last_notified_at = pg_catalog.to_timestamp(0)
1931
+ WHERE notify_insert_throttle.queue_name = update_notify_insert.queue_name;
1932
+ END;
1933
+ $$;
1934
+
1935
+ CREATE OR REPLACE FUNCTION pgmq.validate_routing_key(routing_key text)
1936
+ RETURNS boolean
1937
+ LANGUAGE plpgsql
1938
+ IMMUTABLE
1939
+ SET search_path = pg_catalog, pg_temp
1940
+ AS
1941
+ $$
1942
+ BEGIN
1943
+ -- Valid routing key examples:
1944
+ -- "logs.error"
1945
+ -- "app.user-service.auth"
1946
+ -- "system_events.db.connection_failed"
1947
+ --
1948
+ -- Invalid routing key examples:
1949
+ -- "" - empty
1950
+ -- ".logs.error" - starts with dot
1951
+ -- "logs.error." - ends with dot
1952
+ -- "logs..error" - consecutive dots
1953
+ -- "logs.error!" - invalid character
1954
+ -- "logs error" - space not allowed
1955
+ -- "logs.*" - wildcards not allowed in routing keys
1956
+
1957
+ IF routing_key IS NULL OR routing_key = '' THEN
1958
+ RAISE EXCEPTION 'routing_key cannot be NULL or empty';
1959
+ END IF;
1960
+
1961
+ IF length(routing_key) > 255 THEN
1962
+ RAISE EXCEPTION 'routing_key length cannot exceed 255 characters, got % characters', length(routing_key);
1963
+ END IF;
1964
+
1965
+ IF routing_key !~ '^[a-zA-Z0-9._-]+$' THEN
1966
+ RAISE EXCEPTION 'routing_key contains invalid characters. Only alphanumeric, dots, hyphens, and underscores are allowed. Got: %', routing_key;
1967
+ END IF;
1968
+
1969
+ IF routing_key ~ '^\.' THEN
1970
+ RAISE EXCEPTION 'routing_key cannot start with a dot. Got: %', routing_key;
1971
+ END IF;
1972
+
1973
+ IF routing_key ~ '\.$' THEN
1974
+ RAISE EXCEPTION 'routing_key cannot end with a dot. Got: %', routing_key;
1975
+ END IF;
1976
+
1977
+ IF routing_key ~ '\.\.' THEN
1978
+ RAISE EXCEPTION 'routing_key cannot contain consecutive dots. Got: %', routing_key;
1979
+ END IF;
1980
+
1981
+ RETURN true;
1982
+ END;
1983
+ $$;
1984
+
1985
+ CREATE OR REPLACE FUNCTION pgmq.validate_topic_pattern(pattern text)
1986
+ RETURNS boolean
1987
+ LANGUAGE plpgsql
1988
+ IMMUTABLE
1989
+ SET search_path = pg_catalog, pg_temp
1990
+ AS
1991
+ $$
1992
+ BEGIN
1993
+ -- Valid pattern examples:
1994
+ -- "logs.*" - matches one segment after logs. (e.g., logs.error, logs.info)
1995
+ -- "logs.#" - matches one or more segments after logs. (e.g., logs.error, logs.api.error)
1996
+ -- "*.error" - matches one segment before .error (e.g., app.error, db.error)
1997
+ -- "#.error" - matches one or more segments before .error (e.g., app.error, x.y.error)
1998
+ -- "app.*.#" - mixed wildcards (one segment then one or more)
1999
+ -- "#" - catch-all pattern, matches any routing key
2000
+ --
2001
+ -- Invalid pattern examples:
2002
+ -- ".logs.*" - starts with dot
2003
+ -- "logs.*." - ends with dot
2004
+ -- "logs..error" - consecutive dots
2005
+ -- "logs.**" - consecutive stars
2006
+ -- "logs.##" - consecutive hashes
2007
+ -- "logs.*#" - adjacent wildcards
2008
+ -- "logs.error!" - invalid character
2009
+
2010
+ IF pattern IS NULL OR pattern = '' THEN
2011
+ RAISE EXCEPTION 'pattern cannot be NULL or empty';
2012
+ END IF;
2013
+
2014
+ IF length(pattern) > 255 THEN
2015
+ RAISE EXCEPTION 'pattern length cannot exceed 255 characters, got % characters', length(pattern);
2016
+ END IF;
2017
+
2018
+ IF pattern !~ '^[a-zA-Z0-9._\-*#]+$' THEN
2019
+ RAISE EXCEPTION 'pattern contains invalid characters. Only alphanumeric, dots, hyphens, underscores, *, and # are allowed. Got: %', pattern;
2020
+ END IF;
2021
+
2022
+ IF pattern ~ '^\.' THEN
2023
+ RAISE EXCEPTION 'pattern cannot start with a dot. Got: %', pattern;
2024
+ END IF;
2025
+
2026
+ IF pattern ~ '\.$' THEN
2027
+ RAISE EXCEPTION 'pattern cannot end with a dot. Got: %', pattern;
2028
+ END IF;
2029
+
2030
+ IF pattern ~ '\.\.' THEN
2031
+ RAISE EXCEPTION 'pattern cannot contain consecutive dots. Got: %', pattern;
2032
+ END IF;
2033
+
2034
+ IF pattern ~ '\*\*' THEN
2035
+ RAISE EXCEPTION 'pattern cannot contain consecutive stars (**). Use # for multi-segment matching. Got: %', pattern;
2036
+ END IF;
2037
+
2038
+ IF pattern ~ '##' THEN
2039
+ RAISE EXCEPTION 'pattern cannot contain consecutive hashes (##). A single # already matches zero or more segments. Got: %', pattern;
2040
+ END IF;
2041
+
2042
+ IF pattern ~ '\*#' OR pattern ~ '#\*' THEN
2043
+ RAISE EXCEPTION 'pattern cannot contain adjacent wildcards (*# or #*). Separate wildcards with dots. Got: %', pattern;
2044
+ END IF;
2045
+
2046
+ RETURN true;
2047
+ END;
2048
+ $$;
2049
+
2050
+ CREATE OR REPLACE FUNCTION pgmq.bind_topic(pattern text, queue_name text)
2051
+ RETURNS void
2052
+ LANGUAGE plpgsql
2053
+ SET search_path = pg_catalog, pg_temp
2054
+ AS
2055
+ $$
2056
+ BEGIN
2057
+ PERFORM pgmq.validate_topic_pattern(pattern);
2058
+ IF queue_name IS NULL OR queue_name = '' THEN
2059
+ RAISE EXCEPTION 'queue_name cannot be NULL or empty';
2060
+ END IF;
2061
+
2062
+ IF NOT EXISTS (SELECT 1 FROM pgmq.meta WHERE meta.queue_name = bind_topic.queue_name) THEN
2063
+ RAISE EXCEPTION 'Queue "%" does not exist. Create the queue first using pgmq.create()', queue_name;
2064
+ END IF;
2065
+
2066
+ INSERT INTO pgmq.topic_bindings (pattern, queue_name)
2067
+ VALUES (pattern, queue_name)
2068
+ ON CONFLICT ON CONSTRAINT topic_bindings_unique_pattern_queue DO NOTHING;
2069
+ END;
2070
+ $$;
2071
+
2072
+ CREATE OR REPLACE FUNCTION pgmq.unbind_topic(pattern text, queue_name text)
2073
+ RETURNS boolean
2074
+ LANGUAGE plpgsql
2075
+ SET search_path = pg_catalog, pg_temp
2076
+ AS
2077
+ $$
2078
+ DECLARE
2079
+ rows_deleted integer;
2080
+ BEGIN
2081
+ IF pattern IS NULL OR pattern = '' THEN
2082
+ RAISE EXCEPTION 'pattern cannot be NULL or empty';
2083
+ END IF;
2084
+
2085
+ IF queue_name IS NULL OR queue_name = '' THEN
2086
+ RAISE EXCEPTION 'queue_name cannot be NULL or empty';
2087
+ END IF;
2088
+
2089
+ DELETE
2090
+ FROM pgmq.topic_bindings
2091
+ WHERE topic_bindings.pattern = unbind_topic.pattern
2092
+ AND topic_bindings.queue_name = unbind_topic.queue_name;
2093
+
2094
+ GET DIAGNOSTICS rows_deleted = ROW_COUNT;
2095
+
2096
+ IF rows_deleted > 0 THEN
2097
+ RETURN true;
2098
+ ELSE
2099
+ RETURN false;
2100
+ END IF;
2101
+ END;
2102
+ $$;
2103
+
2104
+ CREATE OR REPLACE FUNCTION pgmq.test_routing(routing_key text)
2105
+ RETURNS TABLE
2106
+ (
2107
+ pattern text,
2108
+ queue_name text,
2109
+ compiled_regex text
2110
+ )
2111
+ LANGUAGE plpgsql
2112
+ STABLE
2113
+ SET search_path = pg_catalog, pg_temp
2114
+ AS
2115
+ $$
2116
+ BEGIN
2117
+ PERFORM pgmq.validate_routing_key(routing_key);
2118
+ RETURN QUERY
2119
+ SELECT b.pattern,
2120
+ b.queue_name,
2121
+ b.compiled_regex
2122
+ FROM pgmq.topic_bindings b
2123
+ WHERE routing_key ~ b.compiled_regex
2124
+ ORDER BY b.pattern;
2125
+ END;
2126
+ $$;
2127
+
2128
+ CREATE OR REPLACE FUNCTION pgmq.send_topic(routing_key text, msg jsonb, headers jsonb, delay integer)
2129
+ RETURNS integer
2130
+ LANGUAGE plpgsql
2131
+ VOLATILE
2132
+ SET search_path = pg_catalog, pg_temp
2133
+ AS
2134
+ $$
2135
+ DECLARE
2136
+ b RECORD;
2137
+ matched_count integer := 0;
2138
+ BEGIN
2139
+ PERFORM pgmq.validate_routing_key(routing_key);
2140
+
2141
+ IF msg IS NULL THEN
2142
+ RAISE EXCEPTION 'msg cannot be NULL';
2143
+ END IF;
2144
+
2145
+ IF delay < 0 THEN
2146
+ RAISE EXCEPTION 'delay cannot be negative, got: %', delay;
2147
+ END IF;
2148
+
2149
+ -- Filter matching patterns in SQL for better performance (uses index)
2150
+ -- Any failure will rollback the entire transaction
2151
+ FOR b IN
2152
+ SELECT DISTINCT tb.queue_name
2153
+ FROM pgmq.topic_bindings tb
2154
+ WHERE routing_key ~ tb.compiled_regex
2155
+ ORDER BY tb.queue_name -- Deterministic ordering, deduplicated by queue_name
2156
+ LOOP
2157
+ PERFORM pgmq.send(b.queue_name, msg, headers, delay);
2158
+ matched_count := matched_count + 1;
2159
+ END LOOP;
2160
+
2161
+ RETURN matched_count;
2162
+ END;
2163
+ $$;
2164
+
2165
+ CREATE OR REPLACE FUNCTION pgmq.send_topic(routing_key text, msg jsonb)
2166
+ RETURNS integer
2167
+ LANGUAGE plpgsql
2168
+ VOLATILE
2169
+ SET search_path = pg_catalog, pg_temp
2170
+ AS
2171
+ $$
2172
+ BEGIN
2173
+ RETURN pgmq.send_topic(routing_key, msg, NULL::pg_catalog.jsonb, 0);
2174
+ END;
2175
+ $$;
2176
+
2177
+ CREATE OR REPLACE FUNCTION pgmq.send_topic(routing_key text, msg jsonb, delay integer)
2178
+ RETURNS integer
2179
+ LANGUAGE plpgsql
2180
+ VOLATILE
2181
+ SET search_path = pg_catalog, pg_temp
2182
+ AS
2183
+ $$
2184
+ BEGIN
2185
+ RETURN pgmq.send_topic(routing_key, msg, NULL::pg_catalog.jsonb, delay);
2186
+ END;
2187
+ $$;
2188
+
2189
+ CREATE OR REPLACE FUNCTION pgmq.list_topic_bindings()
2190
+ RETURNS TABLE
2191
+ (
2192
+ pattern text,
2193
+ queue_name text,
2194
+ bound_at TIMESTAMP WITH TIME ZONE,
2195
+ compiled_regex text
2196
+ )
2197
+ LANGUAGE sql
2198
+ STABLE
2199
+ SET search_path = pg_catalog, pg_temp
2200
+ AS
2201
+ $$
2202
+ SELECT pattern, queue_name, bound_at, compiled_regex
2203
+ FROM pgmq.topic_bindings
2204
+ ORDER BY bound_at DESC, pattern, queue_name;
2205
+ $$;
2206
+
2207
+ CREATE OR REPLACE FUNCTION pgmq.list_topic_bindings(queue_name text)
2208
+ RETURNS TABLE
2209
+ (
2210
+ pattern text,
2211
+ queue_name text,
2212
+ bound_at TIMESTAMP WITH TIME ZONE,
2213
+ compiled_regex text
2214
+ )
2215
+ LANGUAGE sql
2216
+ STABLE
2217
+ SET search_path = pg_catalog, pg_temp
2218
+ AS
2219
+ $$
2220
+ SELECT pattern, tb.queue_name, bound_at, compiled_regex
2221
+ FROM pgmq.topic_bindings tb
2222
+ WHERE tb.queue_name = list_topic_bindings.queue_name
2223
+ ORDER BY bound_at DESC, pattern;
2224
+ $$;
2225
+
2226
+ -- send_batch_topic: Base implementation with TIMESTAMP WITH TIME ZONE delay
2227
+ CREATE OR REPLACE FUNCTION pgmq.send_batch_topic(
2228
+ routing_key text,
2229
+ msgs jsonb[],
2230
+ headers jsonb[],
2231
+ delay TIMESTAMP WITH TIME ZONE
2232
+ )
2233
+ RETURNS TABLE(queue_name text, msg_id bigint)
2234
+ LANGUAGE plpgsql
2235
+ VOLATILE
2236
+ SET search_path = pg_catalog, pg_temp
2237
+ AS
2238
+ $$
2239
+ DECLARE
2240
+ b RECORD;
2241
+ BEGIN
2242
+ PERFORM pgmq.validate_routing_key(routing_key);
2243
+
2244
+ -- Validate batch parameters once (not per queue)
2245
+ PERFORM pgmq._validate_batch_params(msgs, headers);
2246
+
2247
+ -- Filter matching patterns in SQL for better performance (uses index)
2248
+ -- Any failure will rollback the entire transaction
2249
+ FOR b IN
2250
+ SELECT DISTINCT tb.queue_name
2251
+ FROM pgmq.topic_bindings tb
2252
+ WHERE routing_key ~ tb.compiled_regex
2253
+ ORDER BY tb.queue_name -- Deterministic ordering, deduplicated by queue_name
2254
+ LOOP
2255
+ -- Use private _send_batch to avoid redundant validation
2256
+ RETURN QUERY
2257
+ SELECT b.queue_name, batch_result.msg_id
2258
+ FROM pgmq._send_batch(b.queue_name, msgs, headers, delay) AS batch_result(msg_id);
2259
+ END LOOP;
2260
+
2261
+ RETURN;
2262
+ END;
2263
+ $$;
2264
+
2265
+ -- send_batch_topic: 2 args (routing_key, msgs)
2266
+ CREATE OR REPLACE FUNCTION pgmq.send_batch_topic(
2267
+ routing_key text,
2268
+ msgs jsonb[]
2269
+ )
2270
+ RETURNS TABLE(queue_name text, msg_id bigint)
2271
+ LANGUAGE sql
2272
+ VOLATILE
2273
+ SET search_path = pg_catalog, pg_temp
2274
+ AS
2275
+ $$
2276
+ SELECT * FROM pgmq.send_batch_topic(routing_key, msgs, NULL::pg_catalog.jsonb[], clock_timestamp());
2277
+ $$;
2278
+
2279
+ -- send_batch_topic: 3 args with headers
2280
+ CREATE OR REPLACE FUNCTION pgmq.send_batch_topic(
2281
+ routing_key text,
2282
+ msgs jsonb[],
2283
+ headers jsonb[]
2284
+ )
2285
+ RETURNS TABLE(queue_name text, msg_id bigint)
2286
+ LANGUAGE sql
2287
+ VOLATILE
2288
+ SET search_path = pg_catalog, pg_temp
2289
+ AS
2290
+ $$
2291
+ SELECT * FROM pgmq.send_batch_topic(routing_key, msgs, headers, clock_timestamp());
2292
+ $$;
2293
+
2294
+ -- send_batch_topic: 3 args with integer delay
2295
+ CREATE OR REPLACE FUNCTION pgmq.send_batch_topic(
2296
+ routing_key text,
2297
+ msgs jsonb[],
2298
+ delay integer
2299
+ )
2300
+ RETURNS TABLE(queue_name text, msg_id bigint)
2301
+ LANGUAGE sql
2302
+ VOLATILE
2303
+ SET search_path = pg_catalog, pg_temp
2304
+ AS
2305
+ $$
2306
+ SELECT * FROM pgmq.send_batch_topic(routing_key, msgs, NULL::pg_catalog.jsonb[], clock_timestamp() + pg_catalog.make_interval(secs => delay));
2307
+ $$;
2308
+
2309
+ -- send_batch_topic: 3 args with timestamp delay
2310
+ CREATE OR REPLACE FUNCTION pgmq.send_batch_topic(
2311
+ routing_key text,
2312
+ msgs jsonb[],
2313
+ delay TIMESTAMP WITH TIME ZONE
2314
+ )
2315
+ RETURNS TABLE(queue_name text, msg_id bigint)
2316
+ LANGUAGE sql
2317
+ VOLATILE
2318
+ SET search_path = pg_catalog, pg_temp
2319
+ AS
2320
+ $$
2321
+ SELECT * FROM pgmq.send_batch_topic(routing_key, msgs, NULL::pg_catalog.jsonb[], delay);
2322
+ $$;
2323
+
2324
+ -- send_batch_topic: 4 args with integer delay
2325
+ CREATE OR REPLACE FUNCTION pgmq.send_batch_topic(
2326
+ routing_key text,
2327
+ msgs jsonb[],
2328
+ headers jsonb[],
2329
+ delay integer
2330
+ )
2331
+ RETURNS TABLE(queue_name text, msg_id bigint)
2332
+ LANGUAGE sql
2333
+ VOLATILE
2334
+ SET search_path = pg_catalog, pg_temp
2335
+ AS
2336
+ $$
2337
+ SELECT * FROM pgmq.send_batch_topic(routing_key, msgs, headers, clock_timestamp() + pg_catalog.make_interval(secs => delay));
2338
+ $$;
2339
+
2340
+ -- A direct statement-by-statement load restores its original session path.
2341
+ -- A load inside a transaction keeps the local setting until commit.
2342
+ DO $pgmq_restore_path$
2343
+ DECLARE
2344
+ saved_path pg_catalog.text := pg_catalog.current_setting('pgmq.install_saved_search_path', true);
2345
+ BEGIN
2346
+ IF pg_catalog.current_setting('pgmq.install_path_override', true)
2347
+ OPERATOR(pg_catalog.=) '1'::pg_catalog.text
2348
+ AND saved_path IS NOT NULL THEN
2349
+ PERFORM pg_catalog.set_config('search_path', saved_path, false);
2350
+ PERFORM pg_catalog.set_config('pgmq.install_saved_search_path', '', false);
2351
+ PERFORM pg_catalog.set_config('pgmq.install_path_override', '0', false);
2352
+ END IF;
2353
+ END
2354
+ $pgmq_restore_path$;