-
Notifications
You must be signed in to change notification settings - Fork 52
/
000-event.sql
674 lines (521 loc) · 22.8 KB
/
000-event.sql
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
/******************************************************************************
* Events
* Pub/sub event system for PostgreSQL
*
* Copyright (c) 2019 - Aquameta - http://aquameta.org/
******************************************************************************/
/************************************************************************
* table event.session
* persistent (cross-connection) session object.
***********************************************************************/
create table event.session (
id uuid not null default public.uuid_generate_v4() primary key,
owner_id meta.role_id not null -- the owner's role
);
/************************************************************************
* function event.session_create()
* create a new event.session
***********************************************************************/
create or replace function event.session_create() returns uuid as $$
declare
session_id uuid;
begin
insert into event.session (owner_id)
values (meta.current_role_id())
returning id into session_id;
return session_id;
end;
$$ language plpgsql;
/************************************************************************
* function event.session_attach()
* attach to an existing session
***********************************************************************/
create or replace function event.session_attach( session_id uuid ) returns void as $$
DECLARE
session_exists boolean;
event json; -- todo jsonb
BEGIN
EXECUTE 'select exists(select 1 from event.session where id=' || quote_literal(session_id) || ')' INTO session_exists;
IF session_exists THEN
EXECUTE 'LISTEN "' || session_id || '"';
-- Send all events in the event table for this session (because they haven't yet been deleted aka recieved by the client)
FOR event IN
EXECUTE 'select event from event.event where session_id=' || quote_literal(session_id)
LOOP
EXECUTE 'NOTIFY "' || session_id || '",' || quote_literal(event);
END LOOP;
END IF;
END;
$$ language plpgsql;
/************************************************************************
* function event.session_detach()
* detach from an existing session
***********************************************************************/
create or replace function event.session_detach( session_id uuid ) returns void as $$
begin
execute 'unlisten "' || session_id || '"';
end;
$$ language plpgsql;
/************************************************************************
* function event.session_delete()
* delete from a session
***********************************************************************/
create or replace function event.session_delete( session_id uuid ) returns void as $$
begin
execute 'delete from event.session where id=' || quote_literal(session_id);
end;
$$ language plpgsql;
/************************************************************************
* subscription tables
* inserting into these tables attaches the 'evented' trigger to the
* specified table, if necessary
***********************************************************************/
-- todo: add trigger that checks to see
create table event.subscription_table (
id uuid not null default public.uuid_generate_v4() primary key,
session_id uuid not null references event.session(id) on delete cascade,
relation_id meta.relation_id,
created_at timestamp not null default now(),
unique (session_id, relation_id)
);
create table event.subscription_column (
id uuid not null default public.uuid_generate_v4() primary key,
session_id uuid not null references event.session(id) on delete cascade,
column_id meta.column_id,
created_at timestamp not null default now(),
unique (session_id, column_id)
);
create table event.subscription_row (
id uuid not null default public.uuid_generate_v4() primary key,
session_id uuid not null references event.session(id) on delete cascade,
row_id meta.row_id,
created_at timestamp not null default now(),
unique (session_id, row_id)
);
create table event.subscription_field (
id uuid not null default public.uuid_generate_v4() primary key,
session_id uuid not null references event.session(id) on delete cascade,
field_id meta.field_id,
created_at timestamp not null default now(),
unique (session_id, field_id)
);
/************************************************************************
* view event.subscription
***********************************************************************/
create view event.subscription as
select s.id,
s.session_id,
'table'::text as type,
s.relation_id,
NULL::meta.column_id as column_id,
NULL::meta.row_id as row_id,
NULL::meta.field_id as field_id
from event.subscription_table s
union
select s.id,
s.session_id,
'column'::text as type,
NULL::meta.relation_id as relation_id,
s.column_id,
NULL::meta.row_id as row_id,
NULL::meta.field_id as field_id
from event.subscription_column s
union
select s.id,
s.session_id,
'row'::text as type,
NULL::meta.relation_id as relation_id,
NULL::meta.column_id as column_id,
s.row_id,
NULL::meta.field_id as field_id
from event.subscription_row s
union
select s.id,
s.session_id,
'field'::text as type,
NULL::meta.relation_id as relation_id,
NULL::meta.column_id as column_id,
NULL::meta.row_id as row_id,
s.field_id
from event.subscription_field s;
/************************************************************************
* event
* this holds sent (NOTIFY'ed) events, and the client is responsible for
* deleting them upon receipt. if the client disconnects, when it
* reattaches, the reattach handler should blast out all the events that
* the client has not yet deleted.
***********************************************************************/
create table event.event (
id uuid not null default public.uuid_generate_v4() primary key,
session_id uuid not null references event.session(id) on delete cascade,
event json,
created_at timestamp not null default now()
);
/************************************************************************
* evented trigger
* this is the trigger that gets attached to any table that someone
* subscribes to. it queries the subscription_* tables looking for
* subscriptions that match this table and, when found, sends the
* subscriber an event.
***********************************************************************/
create or replace function event.event_listener_table() returns trigger as $$
declare
event json; -- TODO: jsonb?
row_id meta.row_id;
event_receiver record;
tmp_boolean boolean;
meta_column_row record;
begin
-- Loop through the relation-level subscriptions (sub_table, sub_column) that match this TG_OP
for event_receiver in
select distinct on (s.session_id) -- No duplicates
s.*,
r.schema_name::text,
r.name::text,
(r.primary_key_column_names[1]).name::text as pk
from meta.relation r
join (
select s.id, s.session_id, 'table' as type, s.relation_id, null::meta.column_id
from event.subscription_table s
union
select s.id, s.session_id, 'column' as type, s.column_id::meta.relation_id, s.column_id
from event.subscription_column s
) s on s.relation_id = r.id
where r.schema_name = TG_TABLE_SCHEMA
and r.name = TG_TABLE_NAME
order by s.session_id, s.type desc
loop
-- DELETE
if TG_OP = 'DELETE' then
-- Get the row_id deleted
execute format('select * from meta.row_id(%L,%L,%L,($1).%I::text)',
event_receiver.schema_name,
event_receiver.name,
event_receiver.pk,
event_receiver.pk)
into row_id
using OLD;
-- Build event payload
event := json_build_object('operation', 'delete', 'subscription_type', event_receiver.type, 'row_id', row_id);
-- Insert this event into the event table
execute 'insert into event.event(session_id, event) values(' || quote_literal(event_receiver.session_id) || ',' || quote_literal(event) || ')';
-- Notify
perform pg_notify(event_receiver.session_id::text, event::text);
continue;
-- INSERT
elsif TG_OP = 'INSERT' then
-- Get the row_id inserted
execute format('select * from meta.row_id(%L,%L,%L,($1).%I::text)',
event_receiver.schema_name,
event_receiver.name,
event_receiver.pk,
event_receiver.pk)
into row_id
using NEW;
-- Build event payload
event := json_build_object('operation', 'insert', 'subscription_type', event_receiver.type, 'row_id', row_id, 'payload', row_to_json(NEW));
-- Insert this event into the event table
execute 'insert into event.event(session_id, event) values(' || quote_literal(event_receiver.session_id) || ',' || quote_literal(event) || ')';
-- Notify
perform pg_notify(event_receiver.session_id::text, event::text);
continue;
-- UPDATE
elsif TG_OP = 'UPDATE' then
-- Get the row_id updated
execute format('select * from meta.row_id(%L,%L,%L,($1).%I::text)',
event_receiver.schema_name,
event_receiver.name,
event_receiver.pk,
event_receiver.pk)
into row_id
using NEW;
-- Loop through columns
for meta_column_row in
select id from meta.column where relation_id = event_receiver.relation_id
loop
-- Skip if wrong column
if event_receiver.type = 'column' and event_receiver.column_id <> meta_column_row.id then
continue;
else
-- Check to see if this column was updated, continue to next column if not
execute 'select $1.' || (meta_column_row.id).name || ' is not distinct from $2.' || (meta_column_row.id).name using NEW, OLD into tmp_boolean;
if tmp_boolean then
continue;
end if;
-- Build payload of changed field
execute
'select json_build_object(''operation'', ''update'', ''subscription_type'', ''' || event_receiver.type || ''', ''row_id'', $1, ''payload'', ' ||
'(select json_build_object(''' || (meta_column_row.id).name || ''', $2.' || (meta_column_row.id).name || ')));'
using row_id, NEW
into event;
-- Insert this event into the event table
execute 'insert into event.event(session_id, event) values(' || quote_literal(event_receiver.session_id) || ',' || quote_literal(event) || ')';
-- Notify
perform pg_notify(event_receiver.session_id::text, event::text);
continue;
end if;
end loop;
continue;
end if;
end loop;
return NULL;
end;
$$ language plpgsql;
/************************************************************************
* evented trigger row
***********************************************************************/
create or replace function event.event_listener_row() returns trigger as $$
declare
event json; -- TODO: jsonb?
row_id meta.row_id;
event_receiver record;
tmp_boolean boolean;
meta_column_row record;
begin
-- Loop through the row-level subscriptions (sub_row, sub_field) that match this TG_OP
for event_receiver in
select distinct on (session_id) -- No duplicates
s.*,
r.schema_name::text,
r.name::text,
(r.primary_key_column_names[1]).name::text as pk
from meta.relation r
join (
select s.id, s.session_id, 'row' as type, s.row_id, null::meta.field_id
from event.subscription_row s
union
select s.id, s.session_id, 'field' as type, (s.field_id).row_id, s.field_id
from event.subscription_field s
) s on s.row_id::meta.relation_id=r.id
where r.schema_name = TG_TABLE_SCHEMA
and r.name = TG_TABLE_NAME
order by s.session_id, s.type desc
loop
-- Need to make sure this is the correct row
execute 'select $1.' || event_receiver.pk || ' is distinct from ' || (event_receiver.row_id).pk_value using OLD into tmp_boolean;
if tmp_boolean then
return null;
end if;
-- DELETE
if TG_OP = 'DELETE' then
-- Get the row_id deleted
execute format('select * from meta.row_id(%L,%L,%L,($1).%I::text)',
event_receiver.schema_name,
event_receiver.name,
event_receiver.pk,
event_receiver.pk)
into row_id
using OLD;
-- Build event payload
event := json_build_object('operation', 'delete', 'subscription_type', event_receiver.type, 'row_id', row_id);
-- Insert this event into the event table
execute 'insert into event.event(session_id, event) values(' || quote_literal(event_receiver.session_id) || ',' || quote_literal(event) || ')';
-- Notify
perform pg_notify(event_receiver.session_id::text, event::text);
continue;
elsif TG_OP = 'UPDATE' then
-- Get the row_id deleted
execute format('select * from meta.row_id(%L,%L,%L,($1).%I::text)',
event_receiver.schema_name,
event_receiver.name,
event_receiver.pk,
event_receiver.pk)
into row_id
using NEW;
-- Loop through columns
for meta_column_row in
select id from meta.column where relation_name = event_receiver.name and schema_name = event_receiver.schema_name
loop
-- Skip if wrong column
if event_receiver.type = 'field' and (event_receiver.field_id).column_id <> meta_column_row.id then
continue;
else
-- Check to see if this column was updated, continue to next column if not
execute 'select $1.' || (meta_column_row.id).name || ' is not distinct from $2.' || (meta_column_row.id).name using NEW, OLD into tmp_boolean;
if tmp_boolean then
continue;
end if;
-- Build payload of changed field
execute
'select json_build_object(''operation'', ''update'', ''subscription_type'', ''' || event_receiver.type || ''', ''row_id'', $1, ''payload'', ' ||
'(select json_build_object(''' || (meta_column_row.id).name || ''', $2.' || (meta_column_row.id).name || ')));'
using row_id, NEW
into event;
-- Insert this event into the event table
execute 'insert into event.event(session_id, event) values(' || quote_literal(event_receiver.session_id) || ',' || quote_literal(event) || ')';
-- Notify
perform pg_notify(event_receiver.session_id::text, event::text);
continue;
end if;
end loop;
continue;
end if;
end loop;
return NULL;
end;
$$ language plpgsql;
/************************************************************************
* function subscribe_table(session_id, relation_id)
* adds a row to the subscription_table table, attaches the trigger
***********************************************************************/
create or replace function event.subscribe_table(
session_id uuid,
relation_id meta.relation_id
) returns void as $$
declare
trigger_exists boolean;
trigger_name text := relation_id.name || '_evented_table';
begin
if 'event.event' = format('%I.%I', (relation_id.schema_id).name, relation_id.name) then
return;
end if;
execute format ('select exists(
select 1
from pg_trigger
where not tgisinternal
and tgname = ''%I''
and tgrelid = ''%I.%I''::regclass
)',
trigger_name,
(relation_id.schema_id).name,
relation_id.name)
into trigger_exists;
if not trigger_exists then
execute format ('create trigger %I '
'after insert or update or delete on %I.%I '
'for each row execute procedure event.event_listener_table()',
trigger_name,
(relation_id.schema_id).name,
relation_id.name);
end if;
insert into event.subscription_table(session_id, relation_id)
values(session_id, relation_id)
on conflict do nothing;
end;
$$ language plpgsql security definer;
/************************************************************************
* function subscribe_column(session_id, column_id)
* adds a row to the subscription_column table, attaches the trigger
***********************************************************************/
create or replace function event.subscribe_column(
session_id uuid,
column_id meta.column_id
) returns void as $$
declare
trigger_exists boolean;
relation_id meta.relation_id;
trigger_name text;
begin
relation_id := column_id.relation_id;
trigger_name := relation_id.name || '_evented_table';
if 'event.event' = format('%I.%I', (relation_id.schema_id).name, relation_id.name) then
return;
end if;
execute format ('select exists(
select 1
from pg_trigger
where not tgisinternal
and tgname = ''%I''
and tgrelid = ''%I.%I''::regclass
)',
trigger_name,
(relation_id.schema_id).name,
relation_id.name)
into trigger_exists;
if not trigger_exists then
execute format ('create trigger %I '
'after insert or update or delete on %I.%I '
'for each row execute procedure event.event_listener_table()',
trigger_name,
(relation_id.schema_id).name,
relation_id.name);
end if;
insert into event.subscription_column(session_id, column_id)
values(session_id, column_id)
on conflict do nothing;
end;
$$ language plpgsql security definer;
/************************************************************************
* function subscribe_row(session_id, row_id)
* adds a row to the subscription_row table, attaches the trigger
***********************************************************************/
create or replace function event.subscribe_row(
session_id uuid,
row_id meta.row_id
) returns void as $$
declare
trigger_exists boolean;
relation_id meta.relation_id;
trigger_name text;
begin
relation_id := (row_id.pk_column_id).relation_id;
trigger_name := relation_id.name || '_evented_row';
if 'event.event' = format('%I.%I', (relation_id.schema_id).name, relation_id.name) then
return;
end if;
execute format ('select exists(
select 1
from pg_trigger
where not tgisinternal
and tgname = ''%I''
and tgrelid = ''%I.%I''::regclass
)',
trigger_name,
(relation_id.schema_id).name,
relation_id.name)
into trigger_exists;
if not trigger_exists then
execute format ('create trigger %I '
'after update or delete on %I.%I '
'for each row execute procedure event.event_listener_row()',
trigger_name,
(relation_id.schema_id).name,
relation_id.name);
end if;
insert into event.subscription_row(session_id, row_id)
values(session_id, row_id)
on conflict do nothing;
end;
$$ language plpgsql security definer;
/************************************************************************
* function subscribe_field(session_id, field_id)
* adds a field to the subscription_field table, attaches the trigger
***********************************************************************/
create or replace function event.subscribe_field(
session_id uuid,
field_id meta.field_id
) returns void as $$
declare
trigger_exists boolean;
relation_id meta.relation_id;
trigger_name text;
begin
relation_id := (field_id.column_id).relation_id;
trigger_name := relation_id.name || '_evented_row';
if 'event.event' = format('%I.%I', (relation_id.schema_id).name, relation_id.name) then
return;
end if;
execute format ('select exists(
select 1
from pg_trigger
where not tgisinternal
and tgname = ''%I''
and tgrelid = ''%I.%I''::regclass
)',
trigger_name,
(relation_id.schema_id).name,
relation_id.name)
into trigger_exists;
if not trigger_exists then
execute format ('create trigger %I '
'after update or delete on %I.%I '
'for each row execute procedure event.event_listener_row()',
trigger_name,
(relation_id.schema_id).name,
relation_id.name);
end if;
insert into event.subscription_field(session_id, field_id)
values(session_id, field_id)
on conflict do nothing;
end;
$$ language plpgsql security definer;