-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathpgque-tle.sql
More file actions
7164 lines (6594 loc) · 259 KB
/
Copy pathpgque-tle.sql
File metadata and controls
7164 lines (6594 loc) · 259 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
-- pgque-tle.sql -- Install PgQue as a pg_tle (Trusted Language Extension).
-- Auto-generated by build/transform.sh from sql/pgque.sql. Do not edit by hand.
-- Copyright 2026 Nikolay Samokhvalov. Apache-2.0 license.
-- Includes code derived from PgQ (ISC license, Marko Kreen / Skype Technologies OU).
--
-- pg_tle (Trusted Language Extensions, https://github.com/aws/pg_tle) lets
-- PgQue install via create extension without a C extension binary on disk.
-- After loading this script, the extension is registered with pg_tle and can
-- be created or dropped via the standard create / drop extension commands.
--
-- This file is a psql script: it uses backslash meta-commands (\set
-- ON_ERROR_STOP, \echo), so run it with psql. From other clients (GUI
-- tools, JDBC, direct libpq), call pgtle.install_extension() directly,
-- passing the contents of sql/pgque.sql as the extension body.
--
-- Prerequisites:
-- 1. pg_tle is installed in this database:
-- create extension if not exists pg_tle;
-- 2. The current role is a member of pgtle_admin and has CREATEROLE.
-- Postgres roles are database-cluster-global and cannot be created from
-- inside a TLE install body, so this script pre-creates them.
--
-- Usage:
-- psql -d mydb -f sql/pgque-tle.sql
-- psql -d mydb -c 'create extension pgque;'
--
-- Uninstall:
-- psql -d mydb -f sql/pgque-tle-uninstall.sql
\set ON_ERROR_STOP on
-- Step 1: confirm pg_tle is loaded.
do $$
begin
if not exists (select 1 from pg_catalog.pg_extension where extname = 'pg_tle') then
raise exception 'pg_tle is not available in this database. '
'Add pg_tle to shared_preload_libraries (managed providers: '
'parameter group + reboot; self-hosted: alter system + restart), '
'then run: create extension pg_tle; '
'and grant pgtle_admin to the current role.';
end if;
end $$;
-- Step 2: pre-create the pgque_* roles. Roles are cluster-global and cannot
-- be created from inside a tle install body, so the body's idempotent role
-- creation only succeeds when the roles already exist.
do $$
begin
if not exists (select 1 from pg_catalog.pg_roles where rolname = 'pgque_reader') then
create role pgque_reader;
end if;
if not exists (select 1 from pg_catalog.pg_roles where rolname = 'pgque_writer') then
create role pgque_writer;
end if;
if not exists (select 1 from pg_catalog.pg_roles where rolname = 'pgque_admin') then
create role pgque_admin;
end if;
end $$;
-- Step 3: register the extension body with pg_tle.
-- Same version already registered -> no-op (so deployment scripts can rerun).
-- Different version already registered -> raise so the user goes through the
-- explicit uninstall + reinstall path; pg_tle has no managed upgrade path
-- between unrelated registrations of an extension.
do $wrapper$
declare
existing_version text;
begin
select default_version into existing_version
from pgtle.available_extensions()
where name = 'pgque';
if existing_version = '0.2.0' then
raise notice 'pgque 0.2.0 already registered with pg_tle; skipping install_extension().';
return;
end if;
if existing_version is not null then
raise exception 'pgque is already registered with pg_tle at version % '
'but this script registers version %. Run '
'sql/pgque-tle-uninstall.sql first to remove the existing '
'registration, then re-run this script.',
existing_version, '0.2.0';
end if;
perform pgtle.install_extension(
'pgque',
'0.2.0',
'PgQue — PgQ Universal Edition (zero-bloat Postgres queue)',
$pgque_extension_body$
-- pgque.sql -- PgQ Universal Edition
-- Version: 0.2.0
-- Copyright 2026 Nikolay Samokhvalov. Apache-2.0 license.
-- Includes code derived from PgQ (ISC license, Marko Kreen / Skype Technologies OU).
--
-- Install: \i pgque.sql
-- Start: SELECT pgque.start();
-- Usage: See https://github.com/NikolayS/pgque
create schema if not exists pgque;
-- ======================================================================
-- Section 1: Tables (derived from PgQ)
-- Origin: pgq/structure/tables.sql
--
-- PgQue transformations applied:
-- 1. Schema rename: pgq → pgque (all identifiers, grants, references)
-- 2. txid_current() → pg_current_xact_id()::text::bigint (PG14+ API)
-- 3. txid_snapshot → pg_snapshot (type rename)
-- 4. ev_txid kept as xid8 (required by pg_visible_in_snapshot)
-- 5. queue_per_tx_limit column removed (not supported without C)
-- 6. set default_with_oids removed (deprecated since PG 12)
-- 7. CREATE TABLE → CREATE TABLE IF NOT EXISTS (idempotent install)
-- ======================================================================
-- ----------------------------------------------------------------------
-- Section: Internal Tables
--
-- Overview:
-- pgque.queue - Queue configuration
-- pgque.consumer - Consumer names
-- pgque.subscription - Consumer registrations
-- pgque.tick - Per-queue snapshots (ticks)
-- pgque.event_* - Data tables
-- pgque.retry_queue - Events to be retried later
--
--
-- Standard triggers store events in the pgque.event_* data tables
-- There is one top event table pgque.event_<queue_id> for each queue
-- inherited from pgque.event_template wuith three tables for actual data
-- pgque.event_<queue_id>_0 to pgque.event_<queue_id>_2.
--
-- The active table is rotated at interval, so that if all the consubers
-- have passed some poin the oldes one can be emptied using TRUNCATE command
-- for efficiency
--
--
-- ----------------------------------------------------------------------
-- ----------------------------------------------------------------------
-- Table: pgque.consumer
--
-- Name to id lookup for consumers
--
-- Columns:
-- co_id - consumer's id for internal usage
-- co_name - consumer's id for external usage
-- ----------------------------------------------------------------------
create table if not exists pgque.consumer (
co_id serial,
co_name text not null,
constraint consumer_pkey primary key (co_id),
constraint consumer_name_uq UNIQUE (co_name)
);
-- ----------------------------------------------------------------------
-- Table: pgque.queue
--
-- Information about available queues
--
-- Columns:
-- queue_id - queue id for internal usage
-- queue_name - queue name visible outside
-- queue_ntables - how many data tables the queue has
-- queue_cur_table - which data table is currently active
-- queue_rotation_period - period for data table rotation
-- queue_switch_step1 - tx when rotation happened
-- queue_switch_step2 - tx after rotation was committed
-- queue_switch_time - time when switch happened
-- queue_external_ticker - ticks come from some external sources
-- queue_ticker_paused - ticker is paused
-- queue_disable_insert - disallow pgque.insert_event()
-- queue_ticker_max_count - batch should not contain more events
-- queue_ticker_max_lag - events should not age more
-- queue_ticker_idle_period - how often to tick when no events happen
-- queue_data_pfx - prefix for data table names
-- queue_event_seq - sequence for event id's
-- queue_tick_seq - sequence for tick id's
-- queue_extra_maint - array of functon names to call during maintenance
-- ----------------------------------------------------------------------
create table if not exists pgque.queue (
queue_id serial,
queue_name text not null,
queue_ntables integer not null default 3,
queue_cur_table integer not null default 0,
queue_rotation_period interval not null default '2 hours',
queue_switch_step1 bigint not null default pg_current_xact_id()::text::bigint, -- PgQue transformation: txid_current()→pg_current_xact_id()::text::bigint (PG14+)
queue_switch_step2 bigint default pg_current_xact_id()::text::bigint,
queue_switch_time timestamptz not null default now(),
queue_external_ticker boolean not null default false,
queue_disable_insert boolean not null default false,
queue_ticker_paused boolean not null default false,
queue_ticker_max_count integer not null default 500,
queue_ticker_max_lag interval not null default '3 seconds',
queue_ticker_idle_period interval not null default '1 minute',
queue_data_pfx text not null,
queue_event_seq text not null,
queue_tick_seq text not null,
queue_extra_maint text[],
constraint queue_pkey primary key (queue_id),
constraint queue_name_uq unique (queue_name)
);
-- ----------------------------------------------------------------------
-- Table: pgque.tick
--
-- Snapshots for event batching
--
-- Columns:
-- tick_queue - queue id whose tick it is
-- tick_id - ticks id (per-queue)
-- tick_time - time when tick happened
-- tick_snapshot - transaction state
-- tick_event_seq - last value for event seq
-- ----------------------------------------------------------------------
create table if not exists pgque.tick (
tick_queue int4 not null,
tick_id bigint not null,
tick_time timestamptz not null default now(),
tick_snapshot pg_snapshot not null default pg_current_snapshot(),
tick_event_seq bigint not null, -- may be NULL on upgraded dbs
constraint tick_pkey primary key (tick_queue, tick_id),
constraint tick_queue_fkey foreign key (tick_queue)
references pgque.queue (queue_id)
);
-- ----------------------------------------------------------------------
-- Sequence: pgque.batch_id_seq
--
-- Sequence for batch id's.
-- ----------------------------------------------------------------------
create sequence if not exists pgque.batch_id_seq;
-- ----------------------------------------------------------------------
-- Table: pgque.subscription
--
-- Consumer registration on a queue.
--
-- Columns:
--
-- sub_id - subscription id for internal usage
-- sub_queue - queue id
-- sub_consumer - consumer's id
-- sub_last_tick - last tick the consumer processed
-- sub_batch - shortcut for queue_id/consumer_id/tick_id
-- sub_next_tick - batch end pos
-- ----------------------------------------------------------------------
create table if not exists pgque.subscription (
sub_id serial not null,
sub_queue int4 not null,
sub_consumer int4 not null,
sub_last_tick bigint,
sub_active timestamptz not null default now(),
sub_batch bigint,
sub_next_tick bigint,
constraint subscription_pkey primary key (sub_queue, sub_consumer),
constraint subscription_batch_idx unique (sub_batch),
constraint sub_queue_fkey foreign key (sub_queue)
references pgque.queue (queue_id),
constraint sub_consumer_fkey foreign key (sub_consumer)
references pgque.consumer (co_id)
);
-- ----------------------------------------------------------------------
-- Table: pgque.event_template
--
-- Parent table for all event tables
--
-- Columns:
-- ev_id - event's id, supposed to be unique per queue
-- ev_time - when the event was inserted
-- ev_txid - transaction id which inserted the event
-- ev_owner - subscription id that wanted to retry this
-- ev_retry - how many times the event has been retried, NULL for new events
-- ev_type - consumer/producer can specify what the data fields contain
-- ev_data - data field
-- ev_extra1 - extra data field
-- ev_extra2 - extra data field
-- ev_extra3 - extra data field
-- ev_extra4 - extra data field
-- ----------------------------------------------------------------------
create table if not exists pgque.event_template (
ev_id bigint not null,
ev_time timestamptz not null,
ev_txid xid8 not null default pg_current_xact_id(), -- PgQue transformation: bigint→xid8 (needed for pg_visible_in_snapshot)
ev_owner int4,
ev_retry int4,
ev_type text,
ev_data text,
ev_extra1 text,
ev_extra2 text,
ev_extra3 text,
ev_extra4 text
);
-- ----------------------------------------------------------------------
-- Table: pgque.retry_queue
--
-- Events to be retried. When retry time reaches, they will
-- be put back into main queue.
--
-- Columns:
-- ev_retry_after - time when it should be re-inserted to main queue
-- ev_queue - queue id, used to speed up event copy into queue
-- * - same as pgque.event_template
-- ----------------------------------------------------------------------
create table if not exists pgque.retry_queue (
ev_retry_after timestamptz not null,
ev_queue int4 not null,
like pgque.event_template,
constraint rq_pkey primary key (ev_owner, ev_id),
constraint rq_queue_id_fkey foreign key (ev_queue)
references pgque.queue (queue_id)
);
alter table pgque.retry_queue alter column ev_owner set not null;
alter table pgque.retry_queue alter column ev_txid drop not null;
create index if not exists rq_retry_idx on pgque.retry_queue (ev_retry_after);
-- ======================================================================
-- Section 2: Internal functions (derived from PgQ)
-- Origin: pgq/functions/*.sql
--
-- PgQue transformations applied:
-- 1. Schema rename: pgq → pgque
-- 2. txid_* → pg_* function renames (PG14+ snapshot API)
-- 3. pg_snapshot_xmin/xmax wrapped with ::text::bigint (xid8→bigint)
-- 4. pg_current_xact_id() cast to ::text::bigint (xid8→bigint)
-- 5. SECURITY DEFINER functions get SET search_path = pgque, pg_catalog
-- 6. pgq_node/Londiste hooks removed from maint_operations
-- 7. pg_notify() injected into ticker for LISTEN/NOTIFY wakeup
-- 8. create_queue() rejects queue names > 57 bytes (pg_notify limit)
-- ======================================================================
create or replace function pgque.upgrade_schema()
returns int4 as $$
-- updates table structure if necessary
declare
cnt int4 = 0;
begin
-- pgque.subscription.sub_last_tick: NOT NULL -> NULL
perform 1 from information_schema.columns
where table_schema = 'pgque'
and table_name = 'subscription'
and column_name ='sub_last_tick'
and is_nullable = 'NO';
if found then
alter table pgque.subscription
alter column sub_last_tick
drop not null;
cnt := cnt + 1;
end if;
-- create roles
perform 1 from pg_catalog.pg_roles where rolname = 'pgque_reader';
if not found then
create role pgque_reader;
cnt := cnt + 1;
end if;
perform 1 from pg_catalog.pg_roles where rolname = 'pgque_writer';
if not found then
create role pgque_writer;
cnt := cnt + 1;
end if;
perform 1 from pg_catalog.pg_roles where rolname = 'pgque_admin';
if not found then
create role pgque_admin;
grant pgque_reader to pgque_admin;
grant pgque_writer to pgque_admin;
cnt := cnt + 1;
end if;
perform 1 from pg_attribute
where attrelid = 'pgque.queue'::regclass
and attname = 'queue_extra_maint';
if not found then
alter table pgque.queue add column queue_extra_maint text[];
end if;
return cnt;
end;
$$ language plpgsql;
create or replace function pgque.batch_event_sql(x_batch_id bigint)
returns text as $$
-- ----------------------------------------------------------------------
-- Function: pgque.batch_event_sql(1)
-- Creates SELECT statement that fetches events for this batch.
--
-- Parameters:
-- x_batch_id - ID of a active batch.
--
-- Returns:
-- SQL statement.
-- ----------------------------------------------------------------------
-- ----------------------------------------------------------------------
-- Algorithm description:
-- Given 2 snapshots, sn1 and sn2 with sn1 having xmin1, xmax1
-- and sn2 having xmin2, xmax2 create expression that filters
-- right txid's from event table.
--
-- Simplest solution would be
-- > WHERE ev_txid >= xmin1 AND ev_txid <= xmax2
-- > AND NOT pg_visible_in_snapshot(ev_txid, sn1)
-- > AND pg_visible_in_snapshot(ev_txid, sn2)
--
-- The simple solution has a problem with long transactions (xmin1 very low).
-- All the batches that happen when the long tx is active will need
-- to scan all events in that range. Here is 2 optimizations used:
--
-- 1) Use [xmax1..xmax2] for range scan. That limits the range to
-- txids that actually happened between two snapshots. For txids
-- in the range [xmin1..xmax1] look which ones were actually
-- committed between snapshots and search for them using exact
-- values using IN (..) list.
--
-- 2) As most TX are short, there could be lot of them that were
-- just below xmax1, but were committed before xmax2. So look
-- if there are ID's near xmax1 and lower the range to include
-- them, thus decresing size of IN (..) list.
-- ----------------------------------------------------------------------
declare
rec record;
sql text;
tbl text;
arr text;
part text;
select_fields text;
retry_expr text;
batch record;
begin
select s.sub_last_tick, s.sub_next_tick, s.sub_id, s.sub_queue,
pg_snapshot_xmax(last.tick_snapshot)::text::bigint as tx_start,
pg_snapshot_xmax(cur.tick_snapshot)::text::bigint as tx_end,
last.tick_snapshot as last_snapshot,
cur.tick_snapshot as cur_snapshot
into batch
from pgque.subscription s, pgque.tick last, pgque.tick cur
where s.sub_batch = x_batch_id
and last.tick_queue = s.sub_queue
and last.tick_id = s.sub_last_tick
and cur.tick_queue = s.sub_queue
and cur.tick_id = s.sub_next_tick;
if not found then
raise exception 'batch not found';
end if;
-- load older transactions
arr := '';
for rec in
-- active tx-es in prev_snapshot that were committed in cur_snapshot
select id1 from
pg_snapshot_xip(batch.last_snapshot) id1 left join
pg_snapshot_xip(batch.cur_snapshot) id2 on (id1 = id2)
where id2 is null
order by 1 desc
loop
-- try to avoid big IN expression, so try to include nearby
-- tx'es into range
if batch.tx_start - 100 <= rec.id1::text::bigint then
batch.tx_start := rec.id1::text::bigint;
else
if arr = '' then
arr := '''' || rec.id1::text || '''::xid8';
else
arr := arr || ',''' || rec.id1::text || '''::xid8';
end if;
end if;
end loop;
-- must match pgque.event_template
select_fields := 'select ev_id, ev_time, ev_txid, ev_retry, ev_type,'
|| ' ev_data, ev_extra1, ev_extra2, ev_extra3, ev_extra4';
retry_expr := ' and (ev_owner is null or ev_owner = '
|| batch.sub_id::text || ')';
-- now generate query that goes over all potential tables
sql := '';
for rec in
select xtbl from pgque.batch_event_tables(x_batch_id) xtbl
loop
tbl := pgque.quote_fqname(rec.xtbl);
-- this gets newer queries that definitely are not in prev_snapshot
part := select_fields
|| ' from pgque.tick cur, pgque.tick last, ' || tbl || ' ev '
|| ' where cur.tick_id = ' || batch.sub_next_tick::text
|| ' and cur.tick_queue = ' || batch.sub_queue::text
|| ' and last.tick_id = ' || batch.sub_last_tick::text
|| ' and last.tick_queue = ' || batch.sub_queue::text
|| ' and ev.ev_txid >= ''' || batch.tx_start::text || '''::xid8'
|| ' and ev.ev_txid <= ''' || batch.tx_end::text || '''::xid8'
|| ' and pg_visible_in_snapshot(ev.ev_txid, cur.tick_snapshot)'
|| ' and not pg_visible_in_snapshot(ev.ev_txid, last.tick_snapshot)'
|| retry_expr;
-- now include older tx-es, that were ongoing
-- at the time of prev_snapshot
if arr <> '' then
part := part || ' union all '
|| select_fields || ' from ' || tbl || ' ev '
|| ' where ev.ev_txid in (' || arr || ')'
|| retry_expr;
end if;
if sql = '' then
sql := part;
else
sql := sql || ' union all ' || part;
end if;
end loop;
if sql = '' then
raise exception 'could not construct sql for batch %', x_batch_id;
end if;
return sql || ' order by 1';
end;
$$ language plpgsql; -- no perms needed
create or replace function pgque.batch_event_tables(x_batch_id bigint)
returns setof text as $$
-- ----------------------------------------------------------------------
-- Function: pgque.batch_event_tables(1)
--
-- Returns set of table names where this batch events may reside.
--
-- Parameters:
-- x_batch_id - ID of a active batch.
-- ----------------------------------------------------------------------
declare
nr integer;
tbl text;
use_prev integer;
use_next integer;
batch record;
begin
select
pg_snapshot_xmin(last.tick_snapshot)::text::bigint as tx_min, -- absolute minimum
pg_snapshot_xmax(cur.tick_snapshot)::text::bigint as tx_max, -- absolute maximum
q.queue_data_pfx, q.queue_ntables,
q.queue_cur_table, q.queue_switch_step1, q.queue_switch_step2
into batch
from pgque.tick last, pgque.tick cur, pgque.subscription s, pgque.queue q
where cur.tick_id = s.sub_next_tick
and cur.tick_queue = s.sub_queue
and last.tick_id = s.sub_last_tick
and last.tick_queue = s.sub_queue
and s.sub_batch = x_batch_id
and q.queue_id = s.sub_queue;
if not found then
raise exception 'Cannot find data for batch %', x_batch_id;
end if;
-- if its definitely not in one or other, look into both
if batch.tx_max < batch.queue_switch_step1 then
use_prev := 1;
use_next := 0;
elsif batch.queue_switch_step2 is not null
and (batch.tx_min > batch.queue_switch_step2)
then
use_prev := 0;
use_next := 1;
else
use_prev := 1;
use_next := 1;
end if;
if use_prev then
nr := batch.queue_cur_table - 1;
if nr < 0 then
nr := batch.queue_ntables - 1;
end if;
tbl := batch.queue_data_pfx || '_' || nr::text;
return next tbl;
end if;
if use_next then
tbl := batch.queue_data_pfx || '_' || batch.queue_cur_table::text;
return next tbl;
end if;
return;
end;
$$ language plpgsql; -- no perms needed
create or replace function pgque.event_retry_raw(
x_queue text,
x_consumer text,
x_retry_after timestamptz,
x_ev_id bigint,
x_ev_time timestamptz,
x_ev_retry integer,
x_ev_type text,
x_ev_data text,
x_ev_extra1 text,
x_ev_extra2 text,
x_ev_extra3 text,
x_ev_extra4 text)
returns bigint as $$
-- ----------------------------------------------------------------------
-- Function: pgque.event_retry_raw(12)
--
-- Allows full control over what goes to retry queue.
--
-- Parameters:
-- x_queue - name of the queue
-- x_consumer - name of the consumer
-- x_retry_after - when the event should be processed again
-- x_ev_id - event id
-- x_ev_time - creation time
-- x_ev_retry - retry count
-- x_ev_type - user data
-- x_ev_data - user data
-- x_ev_extra1 - user data
-- x_ev_extra2 - user data
-- x_ev_extra3 - user data
-- x_ev_extra4 - user data
--
-- Returns:
-- Event ID.
-- ----------------------------------------------------------------------
declare
q record;
id bigint;
begin
select sub_id, queue_event_seq, sub_queue into q
from pgque.consumer, pgque.queue, pgque.subscription
where queue_name = x_queue
and co_name = x_consumer
and sub_consumer = co_id
and sub_queue = queue_id;
if not found then
raise exception 'consumer not registered';
end if;
id := x_ev_id;
if id is null then
id := nextval(q.queue_event_seq);
end if;
insert into pgque.retry_queue (ev_retry_after, ev_queue,
ev_id, ev_time, ev_owner, ev_retry,
ev_type, ev_data, ev_extra1, ev_extra2, ev_extra3, ev_extra4)
values (x_retry_after, q.sub_queue,
id, x_ev_time, q.sub_id, x_ev_retry,
x_ev_type, x_ev_data, x_ev_extra1, x_ev_extra2,
x_ev_extra3, x_ev_extra4);
return id;
end;
$$ language plpgsql security definer set search_path = pgque, pg_catalog; -- PgQue transformation: pin search_path (SECURITY DEFINER hardening)
create or replace function pgque.find_tick_helper(
in i_queue_id int4,
in i_prev_tick_id int8,
in i_prev_tick_time timestamptz,
in i_prev_tick_seq int8,
in i_min_count int8,
in i_min_interval interval,
out next_tick_id int8,
out next_tick_time timestamptz,
out next_tick_seq int8)
as $$
-- ----------------------------------------------------------------------
-- Function: pgque.find_tick_helper(6)
--
-- Helper function for pgque.next_batch_custom() to do extended tick search.
-- ----------------------------------------------------------------------
declare
sure boolean;
can_set boolean;
t record;
cnt int8;
ival interval;
begin
-- first, fetch last tick of the queue
select tick_id, tick_time, tick_event_seq into t
from pgque.tick
where tick_queue = i_queue_id
and tick_id > i_prev_tick_id
order by tick_queue desc, tick_id desc
limit 1;
if not found then
return;
end if;
-- check whether batch would end up within reasonable limits
sure := true;
can_set := false;
if i_min_count is not null then
cnt = t.tick_event_seq - i_prev_tick_seq;
if cnt >= i_min_count then
can_set := true;
end if;
if cnt > i_min_count * 2 then
sure := false;
end if;
end if;
if i_min_interval is not null then
ival = t.tick_time - i_prev_tick_time;
if ival >= i_min_interval then
can_set := true;
end if;
if ival > i_min_interval * 2 then
sure := false;
end if;
end if;
-- if last tick too far away, do large scan
if not sure then
select tick_id, tick_time, tick_event_seq into t
from pgque.tick
where tick_queue = i_queue_id
and tick_id > i_prev_tick_id
and ((i_min_count is not null and (tick_event_seq - i_prev_tick_seq) >= i_min_count)
or
(i_min_interval is not null and (tick_time - i_prev_tick_time) >= i_min_interval))
order by tick_queue asc, tick_id asc
limit 1;
can_set := true;
end if;
if can_set then
next_tick_id := t.tick_id;
next_tick_time := t.tick_time;
next_tick_seq := t.tick_event_seq;
end if;
return;
end;
$$ language plpgsql stable;
create or replace function pgque.ticker(i_queue_name text, i_tick_id bigint, i_orig_timestamp timestamptz, i_event_seq bigint)
returns bigint as $$
-- ----------------------------------------------------------------------
-- Function: pgque.ticker(3)
--
-- External ticker: Insert a tick with a particular tick_id and timestamp.
--
-- Parameters:
-- i_queue_name - Name of the queue
-- i_tick_id - Id of new tick.
--
-- Returns:
-- Tick id.
-- ----------------------------------------------------------------------
begin
insert into pgque.tick (tick_queue, tick_id, tick_time, tick_event_seq)
select queue_id, i_tick_id, i_orig_timestamp, i_event_seq
from pgque.queue
where queue_name = i_queue_name
and queue_external_ticker
and not queue_ticker_paused;
if not found then
raise exception 'queue not found or ticker disabled: %', i_queue_name;
end if;
-- make sure seqs stay current
perform pgque.seq_setval(queue_tick_seq, i_tick_id),
pgque.seq_setval(queue_event_seq, i_event_seq)
from pgque.queue
where queue_name = i_queue_name;
-- pgque: notify listeners after tick
perform pg_notify('pgque_' || i_queue_name, i_tick_id::text); -- PgQue transformation: LISTEN/NOTIFY wakeup (not in original PgQ)
return i_tick_id;
end;
$$ language plpgsql security definer set search_path = pgque, pg_catalog;
create or replace function pgque.ticker(i_queue_name text)
returns bigint as $$
-- ----------------------------------------------------------------------
-- Function: pgque.ticker(1)
--
-- Check if tick is needed for the queue and insert it.
--
-- For pgqadm usage.
--
-- Parameters:
-- i_queue_name - Name of the queue
--
-- Returns:
-- Tick id or NULL if no tick was done.
-- ----------------------------------------------------------------------
declare
res bigint;
q record;
state record;
last2 record;
begin
select queue_id, queue_tick_seq, queue_external_ticker,
queue_ticker_max_count, queue_ticker_max_lag,
queue_ticker_idle_period, queue_event_seq,
pgque.seq_getval(queue_event_seq) as event_seq,
queue_ticker_paused
into q
from pgque.queue where queue_name = i_queue_name;
if not found then
raise exception 'no such queue';
end if;
if q.queue_external_ticker then
raise exception 'This queue has external tick source.';
end if;
if q.queue_ticker_paused then
raise exception 'Ticker has been paused for this queue';
end if;
-- load state from last tick
select now() - tick_time as lag,
q.event_seq - tick_event_seq as new_events,
tick_id, tick_time, tick_event_seq,
pg_snapshot_xmax(tick_snapshot)::text::bigint as sxmax,
pg_snapshot_xmin(tick_snapshot)::text::bigint as sxmin
into state
from pgque.tick
where tick_queue = q.queue_id
order by tick_queue desc, tick_id desc
limit 1;
if found then
if state.sxmin > pg_current_xact_id()::text::bigint then
raise exception 'Invalid PgQ state: old xmin=%, old xmax=%, cur txid=%',
state.sxmin, state.sxmax, pg_current_xact_id()::text::bigint;
end if;
if state.new_events < 0 then
raise warning 'Negative new_events? old=% cur=%', state.tick_event_seq, q.event_seq;
end if;
if state.sxmax > pg_current_xact_id()::text::bigint then
raise warning 'Dubious PgQ state: old xmax=%, cur txid=%', state.sxmax, pg_current_xact_id()::text::bigint;
end if;
if state.new_events > 0 then
-- there are new events, should we wait a bit?
if state.new_events < q.queue_ticker_max_count
and state.lag < q.queue_ticker_max_lag
then
return NULL;
end if;
else
-- no new events, should we apply idle period?
-- check previous event from the last one.
select state.tick_time - tick_time as lag
into last2
from pgque.tick
where tick_queue = q.queue_id
and tick_id < state.tick_id
order by tick_queue desc, tick_id desc
limit 1;
if found then
-- gradually decrease the tick frequency
if (state.lag < q.queue_ticker_max_lag / 2)
or
(state.lag < last2.lag * 2
and state.lag < q.queue_ticker_idle_period)
then
return NULL;
end if;
end if;
end if;
end if;
insert into pgque.tick (tick_queue, tick_id, tick_event_seq)
values (q.queue_id, nextval(q.queue_tick_seq), q.event_seq);
-- pgque: notify listeners after tick
perform pg_notify('pgque_' || i_queue_name, currval(q.queue_tick_seq)::text); -- PgQue transformation: LISTEN/NOTIFY wakeup (not in original PgQ)
return currval(q.queue_tick_seq);
end;
$$ language plpgsql security definer set search_path = pgque, pg_catalog;
create or replace function pgque.ticker() returns bigint as $$
-- ----------------------------------------------------------------------
-- Function: pgque.ticker(0)
--
-- Creates ticks for all unpaused queues which dont have external ticker.
--
-- Returns:
-- Number of queues that were processed.
-- ----------------------------------------------------------------------
declare
res bigint;
q record;
begin
res := 0;
for q in
select queue_name from pgque.queue
where not queue_external_ticker
and not queue_ticker_paused
order by queue_name
loop
if pgque.ticker(q.queue_name) > 0 then
res := res + 1;
end if;
end loop;
return res;
end;
$$ language plpgsql security definer set search_path = pgque, pg_catalog;
create or replace function pgque.maint_retry_events()
returns integer as $$
-- ----------------------------------------------------------------------
-- Function: pgque.maint_retry_events(0)
--
-- Moves retry events back to main queue.
--
-- It moves small amount at a time. It should be called
-- until it returns 0
--
-- Returns:
-- Number of events processed.
-- ----------------------------------------------------------------------
declare
cnt integer;
rec record;
begin
cnt := 0;
-- allow only single event mover at a time, without affecting inserts
lock table pgque.retry_queue in share update exclusive mode;
for rec in
select queue_name,
ev_id, ev_time, ev_owner, ev_retry, ev_type, ev_data,
ev_extra1, ev_extra2, ev_extra3, ev_extra4
from pgque.retry_queue, pgque.queue
where ev_retry_after <= current_timestamp
and queue_id = ev_queue
order by ev_retry_after
limit 10
loop
cnt := cnt + 1;
perform pgque.insert_event_raw(rec.queue_name,
rec.ev_id, rec.ev_time, rec.ev_owner, rec.ev_retry,
rec.ev_type, rec.ev_data, rec.ev_extra1, rec.ev_extra2,
rec.ev_extra3, rec.ev_extra4);
delete from pgque.retry_queue
where ev_owner = rec.ev_owner
and ev_id = rec.ev_id;
end loop;
return cnt;
end;
$$ language plpgsql; -- need admin access
create or replace function pgque.maint_rotate_tables_step1(i_queue_name text)
returns integer as $$
-- ----------------------------------------------------------------------
-- Function: pgque.maint_rotate_tables_step1(1)
--
-- Rotate tables for one queue.
--
-- Parameters:
-- i_queue_name - Name of the queue
--
-- Returns:
-- 0
-- ----------------------------------------------------------------------
declare
badcnt integer;
cf record;
nr integer;
tbl text;
lowest_tick_id int8;
lowest_xmin int8;
begin
-- check if needed and load record
select * from pgque.queue into cf
where queue_name = i_queue_name
and queue_rotation_period is not null
and queue_switch_step2 is not null
and queue_switch_time + queue_rotation_period < current_timestamp
for update;
if not found then
return 0;
end if;
-- if DB is in invalid state, stop
if pg_current_xact_id()::text::bigint < cf.queue_switch_step1 then
raise exception 'queue % maint failure: step1=%, current=%',
i_queue_name, cf.queue_switch_step1, pg_current_xact_id()::text::bigint;
end if;
-- find lowest tick for that queue
select min(sub_last_tick) into lowest_tick_id