-
Notifications
You must be signed in to change notification settings - Fork 59
Expand file tree
/
Copy pathstructure.sql
More file actions
1464 lines (1112 loc) · 45.4 KB
/
Copy pathstructure.sql
File metadata and controls
1464 lines (1112 loc) · 45.4 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
SET statement_timeout = 0;
SET lock_timeout = 0;
SET idle_in_transaction_session_timeout = 0;
SET client_encoding = 'UTF8';
SET standard_conforming_strings = on;
SELECT pg_catalog.set_config('search_path', '', false);
SET check_function_bodies = false;
SET xmloption = content;
SET client_min_messages = warning;
SET row_security = off;
--
-- Name: sequent_schema; Type: SCHEMA; Schema: -; Owner: -
--
CREATE SCHEMA sequent_schema;
--
-- Name: aggregate_event_type; Type: TYPE; Schema: sequent_schema; Owner: -
--
CREATE TYPE sequent_schema.aggregate_event_type AS (
aggregate_type text,
aggregate_id uuid,
events_partition_key text,
event_type text,
event_json jsonb
);
--
-- Name: aggregates_that_need_snapshots(uuid, integer); Type: FUNCTION; Schema: sequent_schema; Owner: -
--
CREATE FUNCTION sequent_schema.aggregates_that_need_snapshots(_last_aggregate_id uuid, _limit integer) RETURNS TABLE(aggregate_id uuid)
LANGUAGE plpgsql
SET search_path TO 'sequent_schema'
AS $$
BEGIN
RETURN QUERY SELECT a.aggregate_id
FROM aggregates_that_need_snapshots a
WHERE a.snapshot_outdated_at IS NOT NULL
AND (_last_aggregate_id IS NULL OR a.aggregate_id > _last_aggregate_id)
ORDER BY 1
LIMIT _limit;
END;
$$;
--
-- Name: delete_all_snapshots(timestamp with time zone); Type: PROCEDURE; Schema: sequent_schema; Owner: -
--
CREATE PROCEDURE sequent_schema.delete_all_snapshots(IN _now timestamp with time zone DEFAULT now())
LANGUAGE plpgsql
SET search_path TO 'sequent_schema'
AS $$
BEGIN
UPDATE aggregates_that_need_snapshots
SET snapshot_outdated_at = _now
WHERE snapshot_outdated_at IS NULL;
DELETE FROM snapshot_records;
END;
$$;
--
-- Name: delete_snapshots_before(uuid, integer, timestamp with time zone); Type: PROCEDURE; Schema: sequent_schema; Owner: -
--
CREATE PROCEDURE sequent_schema.delete_snapshots_before(IN _aggregate_id uuid, IN _sequence_number integer, IN _now timestamp with time zone DEFAULT now())
LANGUAGE plpgsql
SET search_path TO 'sequent_schema'
AS $$
BEGIN
DELETE FROM snapshot_records
WHERE aggregate_id = _aggregate_id
AND sequence_number < _sequence_number;
UPDATE aggregates_that_need_snapshots
SET snapshot_outdated_at = _now
WHERE aggregate_id = _aggregate_id
AND snapshot_outdated_at IS NULL
AND NOT EXISTS (SELECT 1 FROM snapshot_records WHERE aggregate_id = _aggregate_id);
END;
$$;
SET default_tablespace = '';
--
-- Name: commands; Type: TABLE; Schema: sequent_schema; Owner: -
--
CREATE TABLE sequent_schema.commands (
id bigint NOT NULL,
created_at timestamp with time zone NOT NULL,
user_id uuid,
aggregate_id uuid,
command_type_id smallint NOT NULL,
command_json jsonb NOT NULL,
event_aggregate_id uuid,
event_sequence_number integer
)
PARTITION BY RANGE (id);
--
-- Name: enrich_command_json(sequent_schema.commands); Type: FUNCTION; Schema: sequent_schema; Owner: -
--
CREATE FUNCTION sequent_schema.enrich_command_json(command sequent_schema.commands) RETURNS jsonb
LANGUAGE plpgsql STRICT
SET search_path TO 'sequent_schema'
AS $$
BEGIN
RETURN jsonb_build_object(
'command_type', (SELECT type FROM command_types WHERE command_types.id = command.command_type_id),
'created_at', command.created_at,
'user_id', command.user_id,
'aggregate_id', command.aggregate_id,
'event_aggregate_id', command.event_aggregate_id,
'event_sequence_number', command.event_sequence_number
)
|| command.command_json;
END
$$;
--
-- Name: events; Type: TABLE; Schema: sequent_schema; Owner: -
--
CREATE TABLE sequent_schema.events (
aggregate_id uuid NOT NULL,
partition_key text DEFAULT ''::text NOT NULL,
sequence_number integer NOT NULL,
created_at timestamp with time zone NOT NULL,
command_id bigint NOT NULL,
event_type_id smallint NOT NULL,
event_json jsonb NOT NULL,
xact_id bigint DEFAULT ((pg_current_xact_id())::text)::bigint
)
PARTITION BY RANGE (partition_key);
--
-- Name: enrich_event_json(sequent_schema.events); Type: FUNCTION; Schema: sequent_schema; Owner: -
--
CREATE FUNCTION sequent_schema.enrich_event_json(event sequent_schema.events) RETURNS jsonb
LANGUAGE plpgsql STRICT
SET search_path TO 'sequent_schema'
AS $$
BEGIN
RETURN jsonb_build_object(
'aggregate_id', event.aggregate_id,
'sequence_number', event.sequence_number,
'created_at', event.created_at
)
|| event.event_json;
END
$$;
--
-- Name: load_event(uuid, integer); Type: FUNCTION; Schema: sequent_schema; Owner: -
--
CREATE FUNCTION sequent_schema.load_event(_aggregate_id uuid, _sequence_number integer) RETURNS SETOF sequent_schema.aggregate_event_type
LANGUAGE plpgsql STRICT
SET search_path TO 'sequent_schema'
AS $$
BEGIN
RETURN QUERY SELECT aggregate_types.type,
a.aggregate_id,
a.events_partition_key,
event_types.type,
enrich_event_json(e)
FROM aggregates a
INNER JOIN events e ON (a.events_partition_key, a.aggregate_id) = (e.partition_key, e.aggregate_id)
INNER JOIN aggregate_types ON a.aggregate_type_id = aggregate_types.id
INNER JOIN event_types ON e.event_type_id = event_types.id
WHERE a.aggregate_id = _aggregate_id
AND e.sequence_number = _sequence_number;
END;
$$;
--
-- Name: load_events(jsonb, boolean, timestamp with time zone); Type: FUNCTION; Schema: sequent_schema; Owner: -
--
CREATE FUNCTION sequent_schema.load_events(_aggregate_ids jsonb, _use_snapshots boolean DEFAULT true, _until timestamp with time zone DEFAULT NULL::timestamp with time zone) RETURNS SETOF sequent_schema.aggregate_event_type
LANGUAGE plpgsql
SET search_path TO 'sequent_schema'
AS $$
DECLARE
_aggregate_id aggregates.aggregate_id%TYPE;
BEGIN
FOR _aggregate_id IN SELECT * FROM jsonb_array_elements_text(_aggregate_ids) LOOP
-- Use a single query to avoid race condition with UPDATEs to the events partition key
-- in case transaction isolation level is lower than repeatable read (the default of
-- PostgreSQL is read committed).
RETURN QUERY WITH
aggregate AS (
SELECT aggregate_types.type, aggregate_id, events_partition_key
FROM aggregates
JOIN aggregate_types ON aggregate_type_id = aggregate_types.id
WHERE aggregate_id = _aggregate_id
),
snapshot AS (
SELECT *
FROM snapshot_records
WHERE _use_snapshots
AND aggregate_id = _aggregate_id
AND (_until IS NULL OR created_at < _until)
ORDER BY sequence_number DESC LIMIT 1
)
(SELECT a.*, s.snapshot_type, s.snapshot_json FROM aggregate a, snapshot s)
UNION ALL
(SELECT a.*, event_types.type, enrich_event_json(e)
FROM aggregate a
JOIN events e ON (a.events_partition_key, a.aggregate_id) = (e.partition_key, e.aggregate_id)
JOIN event_types ON e.event_type_id = event_types.id
WHERE e.sequence_number >= COALESCE((SELECT sequence_number FROM snapshot), 0)
AND (_until IS NULL OR e.created_at < _until)
ORDER BY e.sequence_number ASC);
END LOOP;
END;
$$;
--
-- Name: load_latest_snapshot(uuid); Type: FUNCTION; Schema: sequent_schema; Owner: -
--
CREATE FUNCTION sequent_schema.load_latest_snapshot(_aggregate_id uuid) RETURNS sequent_schema.aggregate_event_type
LANGUAGE sql
SET search_path TO 'sequent_schema'
AS $$
SELECT (SELECT type FROM aggregate_types WHERE id = a.aggregate_type_id),
a.aggregate_id,
a.events_partition_key,
s.snapshot_type,
s.snapshot_json
FROM aggregates a JOIN snapshot_records s ON a.aggregate_id = s.aggregate_id
WHERE a.aggregate_id = _aggregate_id
ORDER BY s.sequence_number DESC
LIMIT 1;
$$;
--
-- Name: permanently_delete_commands_without_events(uuid); Type: PROCEDURE; Schema: sequent_schema; Owner: -
--
CREATE PROCEDURE sequent_schema.permanently_delete_commands_without_events(IN _aggregate_id uuid)
LANGUAGE plpgsql
SET search_path TO 'sequent_schema'
AS $$
BEGIN
IF _aggregate_id IS NULL THEN
RAISE EXCEPTION 'aggregate_id must be specified to delete commands';
END IF;
DELETE FROM commands
WHERE aggregate_id = _aggregate_id
AND NOT EXISTS (SELECT 1 FROM events WHERE command_id = commands.id);
END;
$$;
--
-- Name: permanently_delete_event_streams(jsonb); Type: PROCEDURE; Schema: sequent_schema; Owner: -
--
CREATE PROCEDURE sequent_schema.permanently_delete_event_streams(IN _aggregate_ids jsonb)
LANGUAGE plpgsql
SET search_path TO 'sequent_schema'
AS $$
BEGIN
DELETE FROM events
USING jsonb_array_elements_text(_aggregate_ids) AS ids (id)
JOIN aggregates ON ids.id::uuid = aggregates.aggregate_id
WHERE events.partition_key = aggregates.events_partition_key
AND events.aggregate_id = aggregates.aggregate_id;
DELETE FROM aggregates
USING jsonb_array_elements_text(_aggregate_ids) AS ids (id)
WHERE aggregates.aggregate_id = ids.id::uuid;
END;
$$;
--
-- Name: register_types(jsonb); Type: PROCEDURE; Schema: sequent_schema; Owner: -
--
CREATE PROCEDURE sequent_schema.register_types(IN _types jsonb)
LANGUAGE plpgsql
SET search_path TO 'sequent_schema'
AS $$
BEGIN
WITH types AS (
SELECT DISTINCT type
FROM jsonb_array_elements_text(_types->'command_types') AS type
EXCEPT
SELECT type FROM command_types
)
INSERT INTO command_types (type)
SELECT type FROM types
ORDER BY 1
ON CONFLICT DO NOTHING;
WITH types AS (
SELECT DISTINCT type AS type
FROM jsonb_array_elements_text(_types->'aggregate_types') AS type
EXCEPT
SELECT type FROM aggregate_types
)
INSERT INTO aggregate_types (type)
SELECT type FROM types
ORDER BY 1
ON CONFLICT DO NOTHING;
WITH types AS (
SELECT DISTINCT type AS type
FROM jsonb_array_elements_text(_types->'event_types') AS type
EXCEPT
SELECT type FROM event_types
)
INSERT INTO event_types (type)
SELECT type FROM types
ORDER BY 1
ON CONFLICT DO NOTHING;
END;
$$;
--
-- Name: save_events_on_delete_trigger(); Type: FUNCTION; Schema: sequent_schema; Owner: -
--
CREATE FUNCTION sequent_schema.save_events_on_delete_trigger() RETURNS trigger
LANGUAGE plpgsql
SET search_path TO 'sequent_schema'
AS $$
BEGIN
INSERT INTO saved_event_records (operation, timestamp, "user", aggregate_id, partition_key, sequence_number, created_at, event_type, event_json, command_id, xact_id)
SELECT 'D',
statement_timestamp(),
user,
o.aggregate_id,
o.partition_key,
o.sequence_number,
o.created_at,
(SELECT type FROM event_types WHERE event_types.id = o.event_type_id),
o.event_json,
o.command_id,
o.xact_id
FROM old_table o;
RETURN NULL;
END;
$$;
--
-- Name: save_events_on_update_trigger(); Type: FUNCTION; Schema: sequent_schema; Owner: -
--
CREATE FUNCTION sequent_schema.save_events_on_update_trigger() RETURNS trigger
LANGUAGE plpgsql
SET search_path TO 'sequent_schema'
AS $$
BEGIN
INSERT INTO saved_event_records (operation, timestamp, "user", aggregate_id, partition_key, sequence_number, created_at, event_type, event_json, command_id, xact_id)
SELECT 'U',
statement_timestamp(),
user,
o.aggregate_id,
o.partition_key,
o.sequence_number,
o.created_at,
(SELECT type FROM event_types WHERE event_types.id = o.event_type_id),
o.event_json,
o.command_id,
o.xact_id
FROM old_table o LEFT JOIN new_table n ON o.aggregate_id = n.aggregate_id AND o.sequence_number = n.sequence_number
WHERE n IS NULL
-- Only save when event related information changes
OR o.created_at <> n.created_at
OR o.event_type_id <> n.event_type_id
OR o.event_json <> n.event_json;
RETURN NULL;
END;
$$;
--
-- Name: select_aggregates_for_snapshotting(integer, timestamp with time zone, timestamp with time zone); Type: FUNCTION; Schema: sequent_schema; Owner: -
--
CREATE FUNCTION sequent_schema.select_aggregates_for_snapshotting(_limit integer, _reschedule_snapshot_scheduled_before timestamp with time zone, _now timestamp with time zone DEFAULT now()) RETURNS TABLE(aggregate_id uuid)
LANGUAGE plpgsql
SET search_path TO 'sequent_schema'
AS $$
BEGIN
RETURN QUERY WITH scheduled AS MATERIALIZED (
SELECT a.aggregate_id
FROM aggregates_that_need_snapshots AS a
WHERE snapshot_outdated_at IS NOT NULL
ORDER BY snapshot_outdated_at ASC, snapshot_sequence_number_high_water_mark DESC, aggregate_id ASC
LIMIT _limit
FOR UPDATE
) UPDATE aggregates_that_need_snapshots AS row
SET snapshot_scheduled_at = _now
FROM scheduled
WHERE row.aggregate_id = scheduled.aggregate_id
AND (row.snapshot_scheduled_at IS NULL OR row.snapshot_scheduled_at < _reschedule_snapshot_scheduled_before)
RETURNING row.aggregate_id;
END;
$$;
--
-- Name: store_aggregates(jsonb); Type: PROCEDURE; Schema: sequent_schema; Owner: -
--
CREATE PROCEDURE sequent_schema.store_aggregates(IN _aggregates_with_events jsonb)
LANGUAGE plpgsql
SET search_path TO 'sequent_schema'
AS $$
DECLARE
_aggregate jsonb;
_events jsonb;
_aggregate_id aggregates.aggregate_id%TYPE;
_events_partition_key aggregates.events_partition_key%TYPE;
_current_partition_key aggregates.events_partition_key%TYPE;
_snapshot_outdated_at aggregates_that_need_snapshots.snapshot_outdated_at%TYPE;
BEGIN
FOR _aggregate, _events IN SELECT row->0, row->1 FROM jsonb_array_elements(_aggregates_with_events) AS row ORDER BY row->0->>'aggregate_id' LOOP
_aggregate_id = _aggregate->>'aggregate_id';
_events_partition_key = COALESCE(_aggregate->>'events_partition_key', '');
INSERT INTO aggregates (aggregate_id, created_at, aggregate_type_id, events_partition_key)
VALUES (
_aggregate_id,
(_events->0->>'created_at')::timestamptz,
(SELECT id FROM aggregate_types WHERE type = _aggregate->>'aggregate_type'),
_events_partition_key
) ON CONFLICT (aggregate_id) DO NOTHING;
_current_partition_key = (SELECT events_partition_key FROM aggregates WHERE aggregate_id = _aggregate_id);
IF _current_partition_key <> _events_partition_key THEN
INSERT INTO partition_key_changes AS row (aggregate_id, old_partition_key, new_partition_key)
VALUES (_aggregate_id, _current_partition_key, _events_partition_key)
ON CONFLICT (aggregate_id)
DO UPDATE SET new_partition_key = EXCLUDED.new_partition_key,
updated_at = NOW()
WHERE row.new_partition_key IS DISTINCT FROM EXCLUDED.new_partition_key;
ELSE
DELETE FROM partition_key_changes WHERE aggregate_id = _aggregate_id;
END IF;
_snapshot_outdated_at = _aggregate->>'snapshot_outdated_at';
IF _snapshot_outdated_at IS NOT NULL THEN
INSERT INTO aggregates_that_need_snapshots AS row (aggregate_id, snapshot_outdated_at)
VALUES (_aggregate_id, _snapshot_outdated_at)
ON CONFLICT (aggregate_id) DO UPDATE
SET snapshot_outdated_at = LEAST(row.snapshot_outdated_at, EXCLUDED.snapshot_outdated_at)
WHERE row.snapshot_outdated_at IS DISTINCT FROM EXCLUDED.snapshot_outdated_at;
END IF;
END LOOP;
END;
$$;
--
-- Name: store_command(jsonb); Type: FUNCTION; Schema: sequent_schema; Owner: -
--
CREATE FUNCTION sequent_schema.store_command(_command jsonb) RETURNS bigint
LANGUAGE plpgsql STRICT
SET search_path TO 'sequent_schema'
AS $$
DECLARE
_id commands.id%TYPE;
_command_json jsonb = _command->'command_json';
BEGIN
INSERT INTO commands (
created_at, user_id, aggregate_id, command_type_id, command_json,
event_aggregate_id, event_sequence_number
) VALUES (
(_command->>'created_at')::timestamptz,
(_command_json->>'user_id')::uuid,
(_command_json->>'aggregate_id')::uuid,
(SELECT id FROM command_types WHERE type = _command->>'command_type'),
(_command->'command_json') - '{command_type,created_at,user_id,aggregate_id,event_aggregate_id,event_sequence_number}'::text[],
(_command_json->>'event_aggregate_id')::uuid,
NULLIF(_command_json->'event_sequence_number', 'null'::jsonb)::integer
) RETURNING id INTO STRICT _id;
RETURN _id;
END;
$$;
--
-- Name: store_events(jsonb, jsonb); Type: PROCEDURE; Schema: sequent_schema; Owner: -
--
CREATE PROCEDURE sequent_schema.store_events(IN _command jsonb, IN _aggregates_with_events jsonb)
LANGUAGE plpgsql
SET search_path TO 'sequent_schema'
AS $$
DECLARE
_command_id commands.id%TYPE;
_aggregates jsonb;
_aggregate jsonb;
_events jsonb;
_aggregate_id aggregates.aggregate_id%TYPE;
_events_partition_key aggregates.events_partition_key%TYPE;
_last_sequence_number events.sequence_number%TYPE;
_next_sequence_number events.sequence_number%TYPE;
BEGIN
CALL update_types(_command, _aggregates_with_events);
_command_id = store_command(_command);
CALL store_aggregates(_aggregates_with_events);
FOR _aggregate, _events IN SELECT row->0, row->1 FROM jsonb_array_elements(_aggregates_with_events) AS row
ORDER BY row->0->'aggregate_id', row->1->0->'event_json'->'sequence_number'
LOOP
_aggregate_id = _aggregate->>'aggregate_id';
SELECT events_partition_key INTO STRICT _events_partition_key FROM aggregates WHERE aggregate_id = _aggregate_id;
SELECT MAX(sequence_number)
INTO _last_sequence_number
FROM events
WHERE partition_key = _events_partition_key
AND aggregate_id = _aggregate_id;
SELECT MIN(event->>'sequence_number')
INTO _next_sequence_number
FROM jsonb_array_elements(_events) AS event;
-- Check sequence number of first new event to ensure optimistic locking works correctly
-- (otherwise two concurrent transactions could insert events with different first/next
-- sequence number and no constraint violation would be raised).
IF _last_sequence_number IS NULL AND _next_sequence_number <> 1 THEN
RAISE EXCEPTION 'sequence_number of first event must be 1';
ELSIF _last_sequence_number IS NOT NULL AND _next_sequence_number <= _last_sequence_number + 1 THEN
RAISE EXCEPTION 'sequence_number must be consecutive';
END IF;
INSERT INTO events (partition_key, aggregate_id, sequence_number, created_at, command_id, event_type_id, event_json)
SELECT _events_partition_key,
_aggregate_id,
(event->'event_json'->'sequence_number')::integer,
(event->>'created_at')::timestamptz,
_command_id,
(SELECT id FROM event_types WHERE type = event->>'event_type'),
(event->'event_json') - '{aggregate_id,created_at,event_type,sequence_number}'::text[]
FROM jsonb_array_elements(_events) AS event
ORDER BY 1, 2;
END LOOP;
_aggregates = (SELECT jsonb_agg(row->0) FROM jsonb_array_elements(_aggregates_with_events) AS row);
CALL update_unique_keys(_aggregates);
END;
$$;
--
-- Name: store_snapshots(jsonb); Type: PROCEDURE; Schema: sequent_schema; Owner: -
--
CREATE PROCEDURE sequent_schema.store_snapshots(IN _snapshots jsonb)
LANGUAGE plpgsql
SET search_path TO 'sequent_schema'
AS $$
DECLARE
_aggregate_id uuid;
_snapshot jsonb;
_sequence_number snapshot_records.sequence_number%TYPE;
BEGIN
FOR _snapshot IN SELECT * FROM jsonb_array_elements(_snapshots) LOOP
_aggregate_id = _snapshot->>'aggregate_id';
_sequence_number = _snapshot->'sequence_number';
INSERT INTO aggregates_that_need_snapshots AS row (aggregate_id, snapshot_sequence_number_high_water_mark)
VALUES (_aggregate_id, _sequence_number)
ON CONFLICT (aggregate_id) DO UPDATE
SET snapshot_sequence_number_high_water_mark =
GREATEST(row.snapshot_sequence_number_high_water_mark, EXCLUDED.snapshot_sequence_number_high_water_mark),
snapshot_outdated_at = NULL,
snapshot_scheduled_at = NULL;
INSERT INTO snapshot_records (aggregate_id, sequence_number, created_at, snapshot_type, snapshot_json)
VALUES (
_aggregate_id,
_sequence_number,
(_snapshot->>'created_at')::timestamptz,
_snapshot->>'snapshot_type',
_snapshot->'snapshot_json'
);
END LOOP;
END;
$$;
--
-- Name: update_types(jsonb, jsonb); Type: PROCEDURE; Schema: sequent_schema; Owner: -
--
CREATE PROCEDURE sequent_schema.update_types(IN _command jsonb, IN _aggregates_with_events jsonb)
LANGUAGE plpgsql
SET search_path TO 'sequent_schema'
AS $$
BEGIN
IF NOT EXISTS (SELECT 1 FROM command_types t WHERE t.type = _command->>'command_type') THEN
-- Only try inserting if it doesn't exist to avoid exhausting the id sequence
INSERT INTO command_types (type)
VALUES (_command->>'command_type')
ON CONFLICT DO NOTHING;
END IF;
WITH types AS (
SELECT DISTINCT row->0->>'aggregate_type' AS type
FROM jsonb_array_elements(_aggregates_with_events) AS row
)
INSERT INTO aggregate_types (type)
SELECT type FROM types
WHERE type NOT IN (SELECT type FROM aggregate_types)
ORDER BY 1
ON CONFLICT DO NOTHING;
WITH types AS (
SELECT DISTINCT events->>'event_type' AS type
FROM jsonb_array_elements(_aggregates_with_events) AS row
CROSS JOIN LATERAL jsonb_array_elements(row->1) AS events
)
INSERT INTO event_types (type)
SELECT type FROM types
WHERE type NOT IN (SELECT type FROM event_types)
ORDER BY 1
ON CONFLICT DO NOTHING;
END;
$$;
--
-- Name: update_unique_keys(jsonb); Type: PROCEDURE; Schema: sequent_schema; Owner: -
--
CREATE PROCEDURE sequent_schema.update_unique_keys(IN _stream_records jsonb)
LANGUAGE plpgsql
SET search_path TO 'sequent_schema'
AS $$
DECLARE
_aggregate jsonb;
_aggregate_id aggregates.aggregate_id%TYPE;
_unique_keys jsonb;
BEGIN
FOR _aggregate IN SELECT aggregate FROM jsonb_array_elements(_stream_records) AS aggregate ORDER BY aggregate->>'aggregate_id' LOOP
_aggregate_id = _aggregate->>'aggregate_id';
_unique_keys = COALESCE(_aggregate->'unique_keys', '{}'::jsonb);
DELETE FROM aggregate_unique_keys AS target
WHERE target.aggregate_id = _aggregate_id
AND NOT (_unique_keys ? target.scope);
END LOOP;
FOR _aggregate IN SELECT aggregate FROM jsonb_array_elements(_stream_records) AS aggregate ORDER BY aggregate->>'aggregate_id' LOOP
_aggregate_id = _aggregate->>'aggregate_id';
_unique_keys = COALESCE(_aggregate->'unique_keys', '{}'::jsonb);
INSERT INTO aggregate_unique_keys AS target (aggregate_id, scope, key)
SELECT _aggregate_id, key, value
FROM jsonb_each(_unique_keys) AS x
ORDER BY 1, 2
ON CONFLICT (aggregate_id, scope) DO UPDATE
SET key = EXCLUDED.key
WHERE target.key <> EXCLUDED.key;
END LOOP;
EXCEPTION
WHEN unique_violation THEN
RAISE unique_violation
USING MESSAGE = 'duplicate unique key value for aggregate ' || (_aggregate->>'aggregate_type') || ' ' || _aggregate_id || ' (' || SQLERRM || ')';
END;
$$;
SET default_table_access_method = heap;
--
-- Name: ar_internal_metadata; Type: TABLE; Schema: public; Owner: -
--
CREATE TABLE public.ar_internal_metadata (
key character varying NOT NULL,
value character varying,
created_at timestamp(6) without time zone NOT NULL,
updated_at timestamp(6) without time zone NOT NULL
);
--
-- Name: schema_migrations; Type: TABLE; Schema: public; Owner: -
--
CREATE TABLE public.schema_migrations (
version character varying NOT NULL
);
--
-- Name: aggregate_types; Type: TABLE; Schema: sequent_schema; Owner: -
--
CREATE TABLE sequent_schema.aggregate_types (
id smallint NOT NULL,
type text NOT NULL
);
--
-- Name: aggregate_types_id_seq; Type: SEQUENCE; Schema: sequent_schema; Owner: -
--
ALTER TABLE sequent_schema.aggregate_types ALTER COLUMN id ADD GENERATED BY DEFAULT AS IDENTITY (
SEQUENCE NAME sequent_schema.aggregate_types_id_seq
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1
);
--
-- Name: aggregate_unique_keys; Type: TABLE; Schema: sequent_schema; Owner: -
--
CREATE TABLE sequent_schema.aggregate_unique_keys (
aggregate_id uuid NOT NULL,
scope text NOT NULL,
key jsonb NOT NULL
);
--
-- Name: aggregates; Type: TABLE; Schema: sequent_schema; Owner: -
--
CREATE TABLE sequent_schema.aggregates (
aggregate_id uuid NOT NULL,
events_partition_key text DEFAULT ''::text NOT NULL,
aggregate_type_id smallint NOT NULL,
created_at timestamp with time zone DEFAULT now() NOT NULL
)
PARTITION BY RANGE (aggregate_id);
--
-- Name: aggregates_default; Type: TABLE; Schema: sequent_schema; Owner: -
--
CREATE TABLE sequent_schema.aggregates_default (
aggregate_id uuid NOT NULL,
events_partition_key text DEFAULT ''::text NOT NULL,
aggregate_type_id smallint NOT NULL,
created_at timestamp with time zone DEFAULT now() NOT NULL
);
--
-- Name: aggregates_that_need_snapshots; Type: TABLE; Schema: sequent_schema; Owner: -
--
CREATE TABLE sequent_schema.aggregates_that_need_snapshots (
aggregate_id uuid NOT NULL,
snapshot_sequence_number_high_water_mark integer,
snapshot_outdated_at timestamp with time zone,
snapshot_scheduled_at timestamp with time zone
);
--
-- Name: TABLE aggregates_that_need_snapshots; Type: COMMENT; Schema: sequent_schema; Owner: -
--
COMMENT ON TABLE sequent_schema.aggregates_that_need_snapshots IS 'Contains a row for every aggregate with more events than its snapshot threshold.';
--
-- Name: COLUMN aggregates_that_need_snapshots.snapshot_sequence_number_high_water_mark; Type: COMMENT; Schema: sequent_schema; Owner: -
--
COMMENT ON COLUMN sequent_schema.aggregates_that_need_snapshots.snapshot_sequence_number_high_water_mark IS 'The highest sequence number of the stored snapshot. Kept when snapshot are deleted to more easily query aggregates that need snapshotting the most';
--
-- Name: COLUMN aggregates_that_need_snapshots.snapshot_outdated_at; Type: COMMENT; Schema: sequent_schema; Owner: -
--
COMMENT ON COLUMN sequent_schema.aggregates_that_need_snapshots.snapshot_outdated_at IS 'Not NULL indicates a snapshot is needed since the stored timestamp';
--
-- Name: COLUMN aggregates_that_need_snapshots.snapshot_scheduled_at; Type: COMMENT; Schema: sequent_schema; Owner: -
--
COMMENT ON COLUMN sequent_schema.aggregates_that_need_snapshots.snapshot_scheduled_at IS 'Not NULL indicates a snapshot is in the process of being taken';
--
-- Name: command_types; Type: TABLE; Schema: sequent_schema; Owner: -
--
CREATE TABLE sequent_schema.command_types (
id smallint NOT NULL,
type text NOT NULL
);
--
-- Name: command_records; Type: VIEW; Schema: sequent_schema; Owner: -
--
CREATE VIEW sequent_schema.command_records AS
SELECT id,
user_id,
aggregate_id,
( SELECT command_types.type
FROM sequent_schema.command_types
WHERE (command_types.id = command.command_type_id)) AS command_type,
sequent_schema.enrich_command_json(command.*) AS command_json,
created_at,
event_aggregate_id,
event_sequence_number
FROM sequent_schema.commands command;
--
-- Name: command_types_id_seq; Type: SEQUENCE; Schema: sequent_schema; Owner: -
--
ALTER TABLE sequent_schema.command_types ALTER COLUMN id ADD GENERATED BY DEFAULT AS IDENTITY (
SEQUENCE NAME sequent_schema.command_types_id_seq
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1
);
--
-- Name: commands_default; Type: TABLE; Schema: sequent_schema; Owner: -
--
CREATE TABLE sequent_schema.commands_default (
id bigint NOT NULL,
created_at timestamp with time zone NOT NULL,
user_id uuid,
aggregate_id uuid,
command_type_id smallint NOT NULL,
command_json jsonb NOT NULL,
event_aggregate_id uuid,
event_sequence_number integer
);
--
-- Name: commands_id_seq; Type: SEQUENCE; Schema: sequent_schema; Owner: -
--
ALTER TABLE sequent_schema.commands ALTER COLUMN id ADD GENERATED BY DEFAULT AS IDENTITY (
SEQUENCE NAME sequent_schema.commands_id_seq
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1
);
--
-- Name: event_types; Type: TABLE; Schema: sequent_schema; Owner: -
--
CREATE TABLE sequent_schema.event_types (
id smallint NOT NULL,
type text NOT NULL
);
--
-- Name: event_records; Type: VIEW; Schema: sequent_schema; Owner: -
--
CREATE VIEW sequent_schema.event_records AS
SELECT aggregate.aggregate_id,
event.partition_key,
event.sequence_number,
event.created_at,
type.type AS event_type,
sequent_schema.enrich_event_json(event.*) AS event_json,
event.command_id AS command_record_id,
event.xact_id
FROM ((sequent_schema.events event
JOIN sequent_schema.aggregates aggregate ON (((aggregate.aggregate_id = event.aggregate_id) AND (aggregate.events_partition_key = event.partition_key))))
JOIN sequent_schema.event_types type ON ((event.event_type_id = type.id)));
--
-- Name: event_types_id_seq; Type: SEQUENCE; Schema: sequent_schema; Owner: -
--
ALTER TABLE sequent_schema.event_types ALTER COLUMN id ADD GENERATED BY DEFAULT AS IDENTITY (
SEQUENCE NAME sequent_schema.event_types_id_seq
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1
);
--
-- Name: events_default; Type: TABLE; Schema: sequent_schema; Owner: -
--
CREATE TABLE sequent_schema.events_default (
aggregate_id uuid NOT NULL,
partition_key text DEFAULT ''::text NOT NULL,
sequence_number integer NOT NULL,
created_at timestamp with time zone NOT NULL,
command_id bigint NOT NULL,
event_type_id smallint NOT NULL,
event_json jsonb NOT NULL,
xact_id bigint DEFAULT ((pg_current_xact_id())::text)::bigint
);
--
-- Name: partition_key_changes; Type: TABLE; Schema: sequent_schema; Owner: -
--
CREATE TABLE sequent_schema.partition_key_changes (
aggregate_id uuid NOT NULL,
old_partition_key text NOT NULL,
new_partition_key text NOT NULL,
created_at timestamp with time zone DEFAULT now() NOT NULL,
updated_at timestamp with time zone DEFAULT now() NOT NULL
);
--
-- Name: saved_event_records; Type: TABLE; Schema: sequent_schema; Owner: -
--
CREATE TABLE sequent_schema.saved_event_records (
operation character varying(1) NOT NULL,
"timestamp" timestamp with time zone NOT NULL,
"user" text NOT NULL,
aggregate_id uuid NOT NULL,
partition_key text DEFAULT ''::text,
sequence_number integer NOT NULL,
created_at timestamp with time zone NOT NULL,
command_id bigint NOT NULL,
event_type text NOT NULL,
event_json jsonb NOT NULL,
xact_id bigint,
CONSTRAINT saved_event_records_operation_check CHECK (((operation)::text = ANY ((ARRAY['U'::character varying, 'D'::character varying])::text[])))
);
--
-- Name: snapshot_records; Type: TABLE; Schema: sequent_schema; Owner: -
--
CREATE TABLE sequent_schema.snapshot_records (
aggregate_id uuid NOT NULL,
sequence_number integer NOT NULL,
created_at timestamp with time zone NOT NULL,
snapshot_type text NOT NULL,
snapshot_json jsonb NOT NULL
);
--
-- Name: stream_records; Type: VIEW; Schema: sequent_schema; Owner: -
--
CREATE VIEW sequent_schema.stream_records AS
SELECT aggregates.aggregate_id,
aggregates.events_partition_key,