forked from xocolatl/periods
-
Notifications
You must be signed in to change notification settings - Fork 0
/
periods--1.1.sql
3301 lines (2890 loc) · 121 KB
/
periods--1.1.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
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
-- complain if script is sourced in psql, rather than via CREATE EXTENSION
\echo Use "CREATE EXTENSION periods" to load this file. \quit
/* This extension is non-relocatable */
CREATE SCHEMA periods;
CREATE TYPE periods.drop_behavior AS ENUM ('CASCADE', 'RESTRICT');
CREATE TYPE periods.fk_actions AS ENUM ('CASCADE', 'SET NULL', 'SET DEFAULT', 'RESTRICT', 'NO ACTION');
CREATE TYPE periods.fk_match_types AS ENUM ('FULL', 'PARTIAL', 'SIMPLE');
/*
* All referencing columns must be either name or regsomething in order for
* pg_dump to work properly. Plain OIDs are not allowed but attribute numbers
* are, so that we don't have to track renames.
*
* Anything declared as regsomething and created for the period (such as the
* "__as_of" function), should be UNIQUE. If Postgres already verifies
* uniqueness, such as constraint names on a table, then we don't need to do it
* also.
*/
CREATE TABLE periods.periods (
table_name regclass NOT NULL,
period_name name NOT NULL,
start_column_name name NOT NULL,
end_column_name name NOT NULL,
range_type regtype NOT NULL,
bounds_check_constraint name NOT NULL,
PRIMARY KEY (table_name, period_name),
CHECK (start_column_name <> end_column_name)
);
SELECT pg_catalog.pg_extension_config_dump('periods.periods', '');
CREATE TABLE periods.system_time_periods (
table_name regclass NOT NULL,
period_name name NOT NULL,
infinity_check_constraint name NOT NULL,
generated_always_trigger name NOT NULL,
write_history_trigger name NOT NULL,
truncate_trigger name NOT NULL,
excluded_column_names name[] NOT NULL DEFAULT '{}',
PRIMARY KEY (table_name, period_name),
FOREIGN KEY (table_name, period_name) REFERENCES periods.periods,
CHECK (period_name = 'system_time')
);
SELECT pg_catalog.pg_extension_config_dump('periods.system_time_periods', '');
COMMENT ON TABLE periods.periods IS 'The main catalog for periods. All "DDL" operations for periods must first take an exclusive lock on this table.';
CREATE VIEW periods.information_schema__periods AS
SELECT current_catalog AS table_catalog,
n.nspname AS table_schema,
c.relname AS table_name,
p.period_name,
p.start_column_name,
p.end_column_name
FROM periods.periods AS p
JOIN pg_catalog.pg_class AS c ON c.oid = p.table_name
JOIN pg_catalog.pg_namespace AS n ON n.oid = c.relnamespace;
CREATE TABLE periods.for_portion_views (
table_name regclass NOT NULL,
period_name name NOT NULL,
view_name regclass NOT NULL,
trigger_name name NOT NULL,
PRIMARY KEY (table_name, period_name),
FOREIGN KEY (table_name, period_name) REFERENCES periods.periods,
UNIQUE (view_name)
);
SELECT pg_catalog.pg_extension_config_dump('periods.for_portion_views', '');
CREATE TABLE periods.unique_keys (
key_name name NOT NULL,
table_name regclass NOT NULL,
column_names name[] NOT NULL,
period_name name NOT NULL,
unique_constraint name NOT NULL,
exclude_constraint name NOT NULL,
PRIMARY KEY (key_name),
FOREIGN KEY (table_name, period_name) REFERENCES periods.periods
);
SELECT pg_catalog.pg_extension_config_dump('periods.unique_keys', '');
COMMENT ON TABLE periods.unique_keys IS 'A registry of UNIQUE/PRIMARY keys using periods WITHOUT OVERLAPS';
CREATE TABLE periods.foreign_keys (
key_name name NOT NULL,
table_name regclass NOT NULL,
column_names name[] NOT NULL,
period_name name NOT NULL,
unique_key name NOT NULL,
match_type periods.fk_match_types NOT NULL DEFAULT 'SIMPLE',
delete_action periods.fk_actions NOT NULL DEFAULT 'NO ACTION',
update_action periods.fk_actions NOT NULL DEFAULT 'NO ACTION',
fk_insert_trigger name NOT NULL,
fk_update_trigger name NOT NULL,
uk_update_trigger name NOT NULL,
uk_delete_trigger name NOT NULL,
PRIMARY KEY (key_name),
FOREIGN KEY (table_name, period_name) REFERENCES periods.periods,
FOREIGN KEY (unique_key) REFERENCES periods.unique_keys,
CHECK (delete_action NOT IN ('CASCADE', 'SET NULL', 'SET DEFAULT')),
CHECK (update_action NOT IN ('CASCADE', 'SET NULL', 'SET DEFAULT'))
);
SELECT pg_catalog.pg_extension_config_dump('periods.foreign_keys', '');
COMMENT ON TABLE periods.foreign_keys IS 'A registry of foreign keys using periods WITHOUT OVERLAPS';
CREATE TABLE periods.system_versioning (
table_name regclass NOT NULL,
period_name name NOT NULL,
history_table_name regclass NOT NULL,
view_name regclass NOT NULL,
func_as_of regprocedure NOT NULL,
func_between regprocedure NOT NULL,
func_between_symmetric regprocedure NOT NULL,
func_from_to regprocedure NOT NULL,
PRIMARY KEY (table_name),
FOREIGN KEY (table_name, period_name) REFERENCES periods.periods,
CHECK (period_name = 'system_time'),
UNIQUE (history_table_name),
UNIQUE (view_name),
UNIQUE (func_as_of),
UNIQUE (func_between),
UNIQUE (func_between_symmetric),
UNIQUE (func_from_to)
);
SELECT pg_catalog.pg_extension_config_dump('periods.system_versioning', '');
COMMENT ON TABLE periods.system_versioning IS 'A registry of tables with SYSTEM VERSIONING';
/*
* These function starting with "_" are private to the periods extension and
* should not be called by outsiders. When all the other functions have been
* translated to C, they will be removed.
*/
CREATE FUNCTION periods._serialize(table_name regclass)
RETURNS void
LANGUAGE sql
AS
$function$
/* XXX: Is this the best way to do locking? */
SELECT pg_catalog.pg_advisory_xact_lock('periods.periods'::regclass::oid::integer, table_name::oid::integer);
$function$;
CREATE FUNCTION periods._choose_name(resizable text[], fixed text DEFAULT NULL, separator text DEFAULT '_', extra integer DEFAULT 2)
RETURNS name
IMMUTABLE
LANGUAGE plpgsql
AS
$function$
#variable_conflict use_variable
DECLARE
max_length integer;
result text;
NAMEDATALEN CONSTANT integer := 64;
BEGIN
/*
* Reduce the resizable texts until they and the fixed text fit in
* NAMEDATALEN. This probably isn't very efficient but it's not on a hot
* code path so we don't care.
*/
SELECT max(length(t))
INTO max_length
FROM unnest(resizable) AS u (t);
LOOP
result := format('%s%s', array_to_string(resizable, separator), separator || fixed);
IF octet_length(result) <= NAMEDATALEN-extra-1 THEN
RETURN result;
END IF;
max_length := max_length - 1;
resizable := ARRAY (
SELECT left(t, max_length)
FROM unnest(resizable) WITH ORDINALITY AS u (t, o)
ORDER BY o
);
END LOOP;
END;
$function$;
CREATE FUNCTION periods._choose_portion_view_name(table_name name, period_name name)
RETURNS name
IMMUTABLE
LANGUAGE plpgsql
AS
$function$
#variable_conflict use_variable
DECLARE
max_length integer;
result text;
NAMEDATALEN CONSTANT integer := 64;
BEGIN
/*
* Reduce the table and period names until they fit in NAMEDATALEN. This
* probably isn't very efficient but it's not on a hot code path so we
* don't care.
*/
max_length := greatest(length(table_name), length(period_name));
LOOP
result := format('%s__for_portion_of_%s', table_name, period_name);
IF octet_length(result) <= NAMEDATALEN-1 THEN
RETURN result;
END IF;
max_length := max_length - 1;
table_name := left(table_name, max_length);
period_name := left(period_name, max_length);
END LOOP;
END;
$function$;
CREATE FUNCTION periods.add_period(
table_name regclass,
period_name name,
start_column_name name,
end_column_name name,
range_type regtype DEFAULT NULL,
bounds_check_constraint name DEFAULT NULL)
RETURNS boolean
LANGUAGE plpgsql
AS
$function$
#variable_conflict use_variable
DECLARE
table_name_only name;
kind "char";
persistence "char";
alter_commands text[] DEFAULT '{}';
start_attnum smallint;
start_type oid;
start_collation oid;
start_notnull boolean;
end_attnum smallint;
end_type oid;
end_collation oid;
end_notnull boolean;
BEGIN
IF table_name IS NULL THEN
RAISE EXCEPTION 'no table name specified';
END IF;
IF period_name IS NULL THEN
RAISE EXCEPTION 'no period name specified';
END IF;
/* Always serialize operations on our catalogs */
PERFORM periods._serialize(table_name);
/*
* REFERENCES:
* SQL:2016 11.27
*/
/* Don't allow anything on system versioning history tables (this will be relaxed later) */
IF EXISTS (SELECT FROM periods.system_versioning AS sv WHERE sv.history_table_name = table_name) THEN
RAISE EXCEPTION 'history tables for SYSTEM VERSIONING cannot have periods';
END IF;
/* Period names are limited to lowercase alphanumeric characters for now */
period_name := lower(period_name);
IF period_name !~ '^[a-z_][0-9a-z_]*$' THEN
RAISE EXCEPTION 'only alphanumeric characters are currently allowed';
END IF;
IF period_name = 'system_time' THEN
RETURN periods.add_system_time_period(table_name, start_column_name, end_column_name);
END IF;
/* Must be a regular persistent base table. SQL:2016 11.27 SR 2 */
SELECT c.relpersistence, c.relkind
INTO persistence, kind
FROM pg_catalog.pg_class AS c
WHERE c.oid = table_name;
IF kind <> 'r' THEN
/*
* The main reason partitioned tables aren't supported yet is simply
* beceuase I haven't put any thought into it.
* Maybe it's trivial, maybe not.
*/
IF kind = 'p' THEN
RAISE EXCEPTION 'partitioned tables are not supported yet';
END IF;
RAISE EXCEPTION 'relation % is not a table', $1;
END IF;
IF persistence <> 'p' THEN
/* We could probably accept unlogged tables but what's the point? */
RAISE EXCEPTION 'table "%" must be persistent', table_name;
END IF;
/*
* Check if period already exists. Actually no other application time
* periods are allowed per spec, but we don't obey that. We can have as
* many application time periods as we want.
*
* SQL:2016 11.27 SR 5.b
*/
IF EXISTS (SELECT FROM periods.periods AS p WHERE (p.table_name, p.period_name) = (table_name, period_name)) THEN
RAISE EXCEPTION 'period for "%" already exists on table "%"', period_name, table_name;
END IF;
/*
* Although we are not creating a new object, the SQL standard says that
* periods are in the same namespace as columns, so prevent that.
*
* SQL:2016 11.27 SR 5.c
*/
IF EXISTS (
SELECT FROM pg_catalog.pg_attribute AS a
WHERE (a.attrelid, a.attname) = (table_name, period_name))
THEN
RAISE EXCEPTION 'a column named "%" already exists for table "%"', period_name, table_name;
END IF;
/*
* Contrary to SYSTEM_TIME periods, the columns must exist already for
* application time periods.
*
* SQL:2016 11.27 SR 5.d
*/
/* Get start column information */
SELECT a.attnum, a.atttypid, a.attcollation, a.attnotnull
INTO start_attnum, start_type, start_collation, start_notnull
FROM pg_catalog.pg_attribute AS a
WHERE (a.attrelid, a.attname) = (table_name, start_column_name);
IF NOT FOUND THEN
RAISE EXCEPTION 'column "%" not found in table "%"', start_column_name, table_name;
END IF;
IF start_attnum < 0 THEN
RAISE EXCEPTION 'system columns cannot be used in periods';
END IF;
/* Get end column information */
SELECT a.attnum, a.atttypid, a.attcollation, a.attnotnull
INTO end_attnum, end_type, end_collation, end_notnull
FROM pg_catalog.pg_attribute AS a
WHERE (a.attrelid, a.attname) = (table_name, end_column_name);
IF NOT FOUND THEN
RAISE EXCEPTION 'column "%" not found in table "%"', end_column_name, table_name;
END IF;
IF end_attnum < 0 THEN
RAISE EXCEPTION 'system columns cannot be used in periods';
END IF;
/*
* Verify compatibility of start/end columns. The standard says these must
* be either date or timestamp, but we allow anything with a corresponding
* range type because why not.
*
* SQL:2016 11.27 SR 5.g
*/
IF start_type <> end_type THEN
RAISE EXCEPTION 'start and end columns must be of same type';
END IF;
IF start_collation <> end_collation THEN
RAISE EXCEPTION 'start and end columns must be of same collation';
END IF;
/* Get the range type that goes with these columns */
IF range_type IS NOT NULL THEN
IF NOT EXISTS (
SELECT FROM pg_catalog.pg_range AS r
WHERE (r.rngtypid, r.rngsubtype, r.rngcollation) = (range_type, start_type, start_collation))
THEN
RAISE EXCEPTION 'range "%" does not match data type "%"', range_type, start_type;
END IF;
ELSE
SELECT r.rngtypid
INTO range_type
FROM pg_catalog.pg_range AS r
JOIN pg_catalog.pg_opclass AS c ON c.oid = r.rngsubopc
WHERE (r.rngsubtype, r.rngcollation) = (start_type, start_collation)
AND c.opcdefault;
IF NOT FOUND THEN
RAISE EXCEPTION 'no default range type for %', start_type::regtype;
END IF;
END IF;
/*
* Period columns must not be nullable.
*
* SQL:2016 11.27 SR 5.h
*/
IF NOT start_notnull THEN
alter_commands := alter_commands || format('ALTER COLUMN %I SET NOT NULL', start_column_name);
END IF;
IF NOT end_notnull THEN
alter_commands := alter_commands || format('ALTER COLUMN %I SET NOT NULL', end_column_name);
END IF;
/*
* Find and appropriate a CHECK constraint to make sure that start < end.
* Create one if necessary.
*
* SQL:2016 11.27 GR 2.b
*/
DECLARE
condef CONSTANT text := format('CHECK ((%I < %I))', start_column_name, end_column_name);
context text;
BEGIN
IF bounds_check_constraint IS NOT NULL THEN
/* We were given a name, does it exist? */
SELECT pg_catalog.pg_get_constraintdef(c.oid)
INTO context
FROM pg_catalog.pg_constraint AS c
WHERE (c.conrelid, c.conname) = (table_name, bounds_check_constraint)
AND c.contype = 'c';
IF FOUND THEN
/* Does it match? */
IF context <> condef THEN
RAISE EXCEPTION 'constraint "%" on table "%" does not match', bounds_check_constraint, table_name;
END IF;
ELSE
/* If it doesn't exist, we'll use the name for the one we create. */
alter_commands := alter_commands || format('ADD CONSTRAINT %I %s', bounds_check_constraint, condef);
END IF;
ELSE
/* No name given, can we appropriate one? */
SELECT c.conname
INTO bounds_check_constraint
FROM pg_catalog.pg_constraint AS c
WHERE c.conrelid = table_name
AND c.contype = 'c'
AND pg_catalog.pg_get_constraintdef(c.oid) = condef;
/* Make our own then */
IF NOT FOUND THEN
SELECT c.relname
INTO table_name_only
FROM pg_catalog.pg_class AS c
WHERE c.oid = table_name;
bounds_check_constraint := periods._choose_name(ARRAY[table_name_only, period_name], 'check');
alter_commands := alter_commands || format('ADD CONSTRAINT %I %s', bounds_check_constraint, condef);
END IF;
END IF;
END;
/* If we've created any work for ourselves, do it now */
IF alter_commands <> '{}' THEN
EXECUTE format('ALTER TABLE %s %s', table_name, array_to_string(alter_commands, ', '));
END IF;
INSERT INTO periods.periods (table_name, period_name, start_column_name, end_column_name, range_type, bounds_check_constraint)
VALUES (table_name, period_name, start_column_name, end_column_name, range_type, bounds_check_constraint);
RETURN true;
END;
$function$;
CREATE FUNCTION periods.drop_period(table_name regclass, period_name name, drop_behavior periods.drop_behavior DEFAULT 'RESTRICT', purge boolean DEFAULT false)
RETURNS boolean
LANGUAGE plpgsql
AS
$function$
#variable_conflict use_variable
DECLARE
period_row periods.periods;
system_time_period_row periods.system_time_periods;
system_versioning_row periods.system_versioning;
portion_view regclass;
is_dropped boolean;
BEGIN
IF table_name IS NULL THEN
RAISE EXCEPTION 'no table name specified';
END IF;
IF period_name IS NULL THEN
RAISE EXCEPTION 'no period name specified';
END IF;
/* Always serialize operations on our catalogs */
PERFORM periods._serialize(table_name);
/*
* Has the table been dropped already? This could happen if the period is
* being dropped by the drop_protection event trigger or through a DROP
* CASCADE.
*/
is_dropped := NOT EXISTS (SELECT FROM pg_catalog.pg_class AS c WHERE c.oid = table_name);
SELECT p.*
INTO period_row
FROM periods.periods AS p
WHERE (p.table_name, p.period_name) = (table_name, period_name);
IF NOT FOUND THEN
RAISE NOTICE 'period % not found on table %', period_name, table_name;
RETURN false;
END IF;
/* Drop the "for portion" view if it hasn't been dropped already */
PERFORM periods.drop_for_portion_view(table_name, period_name, drop_behavior, purge);
/* If this is a system_time period, get rid of the triggers */
DELETE FROM periods.system_time_periods AS stp
WHERE stp.table_name = table_name
RETURNING stp.* INTO system_time_period_row;
IF FOUND AND NOT is_dropped THEN
EXECUTE format('ALTER TABLE %s DROP CONSTRAINT %I', table_name, system_time_period_row.infinity_check_constraint);
EXECUTE format('DROP TRIGGER %I ON %s', system_time_period_row.generated_always_trigger, table_name);
EXECUTE format('DROP TRIGGER %I ON %s', system_time_period_row.write_history_trigger, table_name);
EXECUTE format('DROP TRIGGER %I ON %s', system_time_period_row.truncate_trigger, table_name);
END IF;
IF drop_behavior = 'RESTRICT' THEN
/* Check for UNIQUE or PRIMARY KEYs */
IF EXISTS (
SELECT FROM periods.unique_keys AS uk
WHERE (uk.table_name, uk.period_name) = (table_name, period_name))
THEN
RAISE EXCEPTION 'period % is part of a UNIQUE or PRIMARY KEY', period_name;
END IF;
/* Check for FOREIGN KEYs */
IF EXISTS (
SELECT FROM periods.foreign_keys AS fk
WHERE (fk.table_name, fk.period_name) = (table_name, period_name))
THEN
RAISE EXCEPTION 'period % is part of a FOREIGN KEY', period_name;
END IF;
/* Check for SYSTEM VERSIONING */
IF EXISTS (
SELECT FROM periods.system_versioning AS sv
WHERE (sv.table_name, sv.period_name) = (table_name, period_name))
THEN
RAISE EXCEPTION 'table % has SYSTEM VERSIONING', table_name;
END IF;
/* Delete bounds check constraint if purging */
IF NOT is_dropped AND purge THEN
EXECUTE format('ALTER TABLE %s DROP CONSTRAINT %I',
table_name, period_row.bounds_check_constraint);
END IF;
/* Remove from catalog */
DELETE FROM periods.periods AS p
WHERE (p.table_name, p.period_name) = (table_name, period_name);
RETURN true;
END IF;
/* We must be in CASCADE mode now */
PERFORM periods.drop_foreign_key(table_name, fk.key_name)
FROM periods.foreign_keys AS fk
WHERE (fk.table_name, fk.period_name) = (table_name, period_name);
PERFORM periods.drop_unique_key(table_name, uk.key_name, drop_behavior, purge)
FROM periods.unique_keys AS uk
WHERE (uk.table_name, uk.period_name) = (table_name, period_name);
/*
* Save ourselves the NOTICE if this table doesn't have SYSTEM
* VERSIONING.
*
* We don't do like above because the purge is different. We don't want
* dropping SYSTEM VERSIONING to drop our infinity constraint; only
* dropping the PERIOD should do that.
*/
IF EXISTS (
SELECT FROM periods.system_versioning AS sv
WHERE (sv.table_name, sv.period_name) = (table_name, period_name))
THEN
PERFORM periods.drop_system_versioning(table_name, drop_behavior, purge);
END IF;
/* Delete bounds check constraint if purging */
IF NOT is_dropped AND purge THEN
EXECUTE format('ALTER TABLE %s DROP CONSTRAINT %I',
table_name, period_row.bounds_check_constraint);
END IF;
/* Remove from catalog */
DELETE FROM periods.periods AS p
WHERE (p.table_name, p.period_name) = (table_name, period_name);
RETURN true;
END;
$function$;
CREATE FUNCTION periods.add_system_time_period(
table_class regclass,
start_column_name name DEFAULT 'system_time_start',
end_column_name name DEFAULT 'system_time_end',
bounds_check_constraint name DEFAULT NULL,
infinity_check_constraint name DEFAULT NULL,
generated_always_trigger name DEFAULT NULL,
write_history_trigger name DEFAULT NULL,
truncate_trigger name DEFAULT NULL,
excluded_column_names name[] DEFAULT '{}')
RETURNS boolean
LANGUAGE plpgsql
AS
$function$
#variable_conflict use_variable
DECLARE
period_name CONSTANT name := 'system_time';
schema_name name;
table_name name;
kind "char";
persistence "char";
alter_commands text[] DEFAULT '{}';
start_attnum smallint;
start_type oid;
start_collation oid;
start_notnull boolean;
end_attnum smallint;
end_type oid;
end_collation oid;
end_notnull boolean;
excluded_column_name name;
DATE_OID CONSTANT integer := 1082;
TIMESTAMP_OID CONSTANT integer := 1114;
TIMESTAMPTZ_OID CONSTANT integer := 1184;
range_type regtype;
BEGIN
IF table_class IS NULL THEN
RAISE EXCEPTION 'no table name specified';
END IF;
/* Always serialize operations on our catalogs */
PERFORM periods._serialize(table_class);
/*
* REFERENCES:
* SQL:2016 4.15.2.2
* SQL:2016 11.7
* SQL:2016 11.27
*/
/* The columns must not be part of UNIQUE keys. SQL:2016 11.7 SR 5)b) */
IF EXISTS (
SELECT FROM periods.unique_keys AS uk
WHERE uk.column_names && ARRAY[start_column_name, end_column_name])
THEN
RAISE EXCEPTION 'columns in period for SYSTEM_TIME are not allowed in UNIQUE keys';
END IF;
/* Must be a regular persistent base table. SQL:2016 11.27 SR 2 */
SELECT n.nspname, c.relname, c.relpersistence, c.relkind
INTO schema_name, table_name, persistence, kind
FROM pg_catalog.pg_class AS c
JOIN pg_catalog.pg_namespace AS n ON n.oid = c.relnamespace
WHERE c.oid = table_class;
IF kind <> 'r' THEN
/*
* The main reason partitioned tables aren't supported yet is simply
* beceuase I haven't put any thought into it.
* Maybe it's trivial, maybe not.
*/
IF kind = 'p' THEN
RAISE EXCEPTION 'partitioned tables are not supported yet';
END IF;
RAISE EXCEPTION 'relation % is not a table', $1;
END IF;
IF persistence <> 'p' THEN
/* We could probably accept unlogged tables but what's the point? */
RAISE EXCEPTION 'table "%" must be persistent', table_class;
END IF;
/*
* Check if period already exists.
*
* SQL:2016 11.27 SR 4.a
*/
IF EXISTS (SELECT FROM periods.periods AS p WHERE (p.table_name, p.period_name) = (table_class, period_name)) THEN
RAISE EXCEPTION 'period for SYSTEM_TIME already exists on table "%"', table_class;
END IF;
/*
* Although we are not creating a new object, the SQL standard says that
* periods are in the same namespace as columns, so prevent that.
*
* SQL:2016 11.27 SR 4.b
*/
IF EXISTS (SELECT FROM pg_catalog.pg_attribute AS a WHERE (a.attrelid, a.attname) = (table_class, period_name)) THEN
RAISE EXCEPTION 'a column named system_time already exists for table "%"', table_class;
END IF;
/* The standard says that the columns must not exist already, but we don't obey that rule for now. */
/* Get start column information */
SELECT a.attnum, a.atttypid, a.attnotnull
INTO start_attnum, start_type, start_notnull
FROM pg_catalog.pg_attribute AS a
WHERE (a.attrelid, a.attname) = (table_class, start_column_name);
IF NOT FOUND THEN
/*
* First add the column with DEFAULT of -infinity to fill the
* current rows, then replace the DEFAULT with transaction_timestamp() for future
* rows.
*
* The default value is just for self-documentation anyway because
* the trigger will enforce the value.
*/
alter_commands := alter_commands || format('ADD COLUMN %I timestamp with time zone NOT NULL DEFAULT ''-infinity''', start_column_name);
start_attnum := 0;
start_type := 'timestamp with time zone'::regtype;
start_notnull := true;
END IF;
alter_commands := alter_commands || format('ALTER COLUMN %I SET DEFAULT transaction_timestamp()', start_column_name);
IF start_attnum < 0 THEN
RAISE EXCEPTION 'system columns cannot be used in periods';
END IF;
/* Get end column information */
SELECT a.attnum, a.atttypid, a.attnotnull
INTO end_attnum, end_type, end_notnull
FROM pg_catalog.pg_attribute AS a
WHERE (a.attrelid, a.attname) = (table_class, end_column_name);
IF NOT FOUND THEN
alter_commands := alter_commands || format('ADD COLUMN %I timestamp with time zone NOT NULL DEFAULT ''infinity''', end_column_name);
end_attnum := 0;
end_type := 'timestamp with time zone'::regtype;
end_notnull := true;
ELSE
alter_commands := alter_commands || format('ALTER COLUMN %I SET DEFAULT ''infinity''', end_column_name);
END IF;
IF end_attnum < 0 THEN
RAISE EXCEPTION 'system columns cannot be used in periods';
END IF;
/* Verify compatibility of start/end columns */
IF start_type::regtype NOT IN ('date', 'timestamp without time zone', 'timestamp with time zone') THEN
RAISE EXCEPTION 'SYSTEM_TIME periods must be of type "date", "timestamp without time zone", or "timestamp with time zone"';
END IF;
IF start_type <> end_type THEN
RAISE EXCEPTION 'start and end columns must be of same type';
END IF;
/* Get appropriate range type */
CASE start_type
WHEN DATE_OID THEN range_type := 'daterange';
WHEN TIMESTAMP_OID THEN range_type := 'tsrange';
WHEN TIMESTAMPTZ_OID THEN range_type := 'tstzrange';
ELSE
RAISE EXCEPTION 'unexpected data type: "%"', start_type::regtype;
END CASE;
/* can't be part of a foreign key */
IF EXISTS (
SELECT FROM periods.foreign_keys AS fk
WHERE fk.table_name = table_class
AND fk.column_names && ARRAY[start_column_name, end_column_name])
THEN
RAISE EXCEPTION 'columns for SYSTEM_TIME must not be part of foreign keys';
END IF;
/*
* Period columns must not be nullable.
*/
IF NOT start_notnull THEN
alter_commands := alter_commands || format('ALTER COLUMN %I SET NOT NULL', start_column_name);
END IF;
IF NOT end_notnull THEN
alter_commands := alter_commands || format('ALTER COLUMN %I SET NOT NULL', end_column_name);
END IF;
/*
* Find and appropriate a CHECK constraint to make sure that start < end.
* Create one if necessary.
*
* SQL:2016 11.27 GR 2.b
*/
DECLARE
condef CONSTANT text := format('CHECK ((%I < %I))', start_column_name, end_column_name);
context text;
BEGIN
IF bounds_check_constraint IS NOT NULL THEN
/* We were given a name, does it exist? */
SELECT pg_catalog.pg_get_constraintdef(c.oid)
INTO context
FROM pg_catalog.pg_constraint AS c
WHERE (c.conrelid, c.conname) = (table_class, bounds_check_constraint)
AND c.contype = 'c';
IF FOUND THEN
/* Does it match? */
IF context <> condef THEN
RAISE EXCEPTION 'constraint "%" on table "%" does not match', bounds_check_constraint, table_class;
END IF;
ELSE
/* If it doesn't exist, we'll use the name for the one we create. */
alter_commands := alter_commands || format('ADD CONSTRAINT %I %s', bounds_check_constraint, condef);
END IF;
ELSE
/* No name given, can we appropriate one? */
SELECT c.conname
INTO bounds_check_constraint
FROM pg_catalog.pg_constraint AS c
WHERE c.conrelid = table_class
AND c.contype = 'c'
AND pg_catalog.pg_get_constraintdef(c.oid) = condef;
/* Make our own then */
IF NOT FOUND THEN
SELECT c.relname
INTO table_name
FROM pg_catalog.pg_class AS c
WHERE c.oid = table_class;
bounds_check_constraint := periods._choose_name(ARRAY[table_name, period_name], 'check');
alter_commands := alter_commands || format('ADD CONSTRAINT %I %s', bounds_check_constraint, condef);
END IF;
END IF;
END;
/*
* Find and appropriate a CHECK constraint to make sure that end = 'infinity'.
* Create one if necessary.
*
* SQL:2016 4.15.2.2
*/
DECLARE
condef CONSTANT text := format('CHECK ((%I = ''infinity''::timestamp with time zone))', end_column_name);
context text;
BEGIN
IF infinity_check_constraint IS NOT NULL THEN
/* We were given a name, does it exist? */
SELECT pg_catalog.pg_get_constraintdef(c.oid)
INTO context
FROM pg_catalog.pg_constraint AS c
WHERE (c.conrelid, c.conname) = (table_class, infinity_check_constraint)
AND c.contype = 'c';
IF FOUND THEN
/* Does it match? */
IF context <> condef THEN
RAISE EXCEPTION 'constraint "%" on table "%" does not match', infinity_check_constraint, table_class;
END IF;
ELSE
/* If it doesn't exist, we'll use the name for the one we create. */
alter_commands := alter_commands || format('ADD CONSTRAINT %I %s', infinity_check_constraint, condef);
END IF;
ELSE
/* No name given, can we appropriate one? */
SELECT c.conname
INTO infinity_check_constraint
FROM pg_catalog.pg_constraint AS c
WHERE c.conrelid = table_class
AND c.contype = 'c'
AND pg_catalog.pg_get_constraintdef(c.oid) = condef;
/* Make our own then */
IF NOT FOUND THEN
SELECT c.relname
INTO table_name
FROM pg_catalog.pg_class AS c
WHERE c.oid = table_class;
infinity_check_constraint := periods._choose_name(ARRAY[table_name, end_column_name], 'infinity_check');
alter_commands := alter_commands || format('ADD CONSTRAINT %I %s', infinity_check_constraint, condef);
END IF;
END IF;
END;
/* If we've created any work for ourselves, do it now */
IF alter_commands <> '{}' THEN
EXECUTE format('ALTER TABLE %I.%I %s', schema_name, table_name, array_to_string(alter_commands, ', '));
IF start_attnum = 0 THEN
SELECT a.attnum
INTO start_attnum
FROM pg_catalog.pg_attribute AS a
WHERE (a.attrelid, a.attname) = (table_class, start_column_name);
END IF;
IF end_attnum = 0 THEN
SELECT a.attnum
INTO end_attnum
FROM pg_catalog.pg_attribute AS a
WHERE (a.attrelid, a.attname) = (table_class, end_column_name);
END IF;
END IF;
/* Make sure all the excluded columns exist */
FOR excluded_column_name IN
SELECT u.name
FROM unnest(excluded_column_names) AS u (name)
WHERE NOT EXISTS (
SELECT FROM pg_catalog.pg_attribute AS a
WHERE (a.attrelid, a.attname) = (table_class, u.name))
LOOP
RAISE EXCEPTION 'column "%" does not exist', excluded_column_name;
END LOOP;
/* Don't allow system columns to be excluded either */
FOR excluded_column_name IN
SELECT u.name
FROM unnest(excluded_column_names) AS u (name)
JOIN pg_catalog.pg_attribute AS a ON (a.attrelid, a.attname) = (table_class, u.name)
WHERE a.attnum < 0
LOOP
RAISE EXCEPTION 'cannot exclude system column "%"', excluded_column_name;
END LOOP;
generated_always_trigger := coalesce(
generated_always_trigger,
periods._choose_name(ARRAY[table_name], 'system_time_generated_always'));
EXECUTE format('CREATE TRIGGER %I BEFORE INSERT OR UPDATE ON %s FOR EACH ROW EXECUTE PROCEDURE periods.generated_always_as_row_start_end()', generated_always_trigger, table_class);
write_history_trigger := coalesce(
write_history_trigger,
periods._choose_name(ARRAY[table_name], 'system_time_write_history'));
EXECUTE format('CREATE TRIGGER %I AFTER INSERT OR UPDATE OR DELETE ON %s FOR EACH ROW EXECUTE PROCEDURE periods.write_history()', write_history_trigger, table_class);
truncate_trigger := coalesce(
truncate_trigger,
periods._choose_name(ARRAY[table_name], 'truncate'));
EXECUTE format('CREATE TRIGGER %I AFTER TRUNCATE ON %s FOR EACH STATEMENT EXECUTE PROCEDURE periods.truncate_system_versioning()', truncate_trigger, table_class);
INSERT INTO periods.periods (table_name, period_name, start_column_name, end_column_name, range_type, bounds_check_constraint)
VALUES (table_class, period_name, start_column_name, end_column_name, range_type, bounds_check_constraint);
INSERT INTO periods.system_time_periods (
table_name, period_name, infinity_check_constraint,
generated_always_trigger, write_history_trigger, truncate_trigger,
excluded_column_names)
VALUES (
table_class, period_name, infinity_check_constraint,
generated_always_trigger, write_history_trigger, truncate_trigger,
excluded_column_names);
RETURN true;
END;
$function$;
CREATE FUNCTION periods.set_system_time_period_excluded_columns(
table_name regclass,
excluded_column_names name[])
RETURNS void
LANGUAGE plpgsql
AS
$function$
#variable_conflict use_variable
DECLARE
excluded_column_name name;
BEGIN
/* Always serialize operations on our catalogs */
PERFORM periods._serialize(table_name);
/* Make sure all the excluded columns exist */
FOR excluded_column_name IN
SELECT u.name