forked from postgrespro/pg_pathman
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pg_pathman--1.0--1.1.sql
1980 lines (1665 loc) · 54.6 KB
/
pg_pathman--1.0--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
/* ------------------------------------------------------------------------
*
* pg_pathman--1.0--1.1.sql
* Migration scripts to version 1.1
*
* Copyright (c) 2015-2016, Postgres Professional
*
* ------------------------------------------------------------------------
*/
/* ------------------------------------------------------------------------
* Modify config params table
* ----------------------------------------------------------------------*/
ALTER TABLE @[email protected]_config_params ADD COLUMN init_callback REGPROCEDURE NOT NULL DEFAULT 0;
ALTER TABLE @[email protected]_config_params ALTER COLUMN enable_parent SET DEFAULT FALSE;
/* ------------------------------------------------------------------------
* Enable permissions
* ----------------------------------------------------------------------*/
GRANT SELECT, INSERT, UPDATE, DELETE
ON @[email protected]_config, @[email protected]_config_params
TO public;
CREATE OR REPLACE FUNCTION @[email protected]_security_policy(relation regclass)
RETURNS BOOL AS 'pg_pathman', 'check_security_policy' LANGUAGE C STRICT;
CREATE POLICY deny_modification ON @[email protected]_config
FOR ALL USING (check_security_policy(partrel));
CREATE POLICY deny_modification ON @[email protected]_config_params
FOR ALL USING (check_security_policy(partrel));
CREATE POLICY allow_select ON @[email protected]_config FOR SELECT USING (true);
CREATE POLICY allow_select ON @[email protected]_config_params FOR SELECT USING (true);
ALTER TABLE @[email protected]_config ENABLE ROW LEVEL SECURITY;
ALTER TABLE @[email protected]_config_params ENABLE ROW LEVEL SECURITY;
GRANT SELECT ON @[email protected]_concurrent_part_tasks TO PUBLIC;
/* ------------------------------------------------------------------------
* Drop irrelevant functions
* ----------------------------------------------------------------------*/
DROP FUNCTION @[email protected]_set_param(REGCLASS, TEXT, BOOLEAN);
DROP FUNCTION @[email protected]_parent(REGCLASS);
DROP FUNCTION @[email protected]_parent(relation REGCLASS);
DROP FUNCTION @[email protected]_auto(relation REGCLASS);
DROP FUNCTION @[email protected]_auto(relation REGCLASS);
DROP FUNCTION @[email protected]_table_concurrently(relation regclass);
DROP FUNCTION @extschema@._partition_data_concurrent(REGCLASS, ANYELEMENT, ANYELEMENT, INT, OUT BIGINT);
DROP FUNCTION @[email protected]_relation_checks(REGCLASS, TEXT);
DROP FUNCTION @[email protected]_attribute_type_name(REGCLASS, TEXT);
DROP FUNCTION @[email protected]_type_hash_func(REGTYPE);
DROP FUNCTION @[email protected]_boundaries(REGCLASS, TEXT, ANYELEMENT, ANYELEMENT);
DROP FUNCTION @[email protected]_range_partitions(REGCLASS, TEXT, ANYELEMENT, INTERVAL, INTEGER, BOOLEAN);
DROP FUNCTION @[email protected]_range_partitions(REGCLASS, TEXT, ANYELEMENT, ANYELEMENT, INTEGER, BOOLEAN);
DROP FUNCTION @[email protected]_partitions_from_range(REGCLASS, TEXT, ANYELEMENT, ANYELEMENT, ANYELEMENT, BOOLEAN);
DROP FUNCTION @[email protected]_partitions_from_range(REGCLASS, TEXT, ANYELEMENT, ANYELEMENT, INTERVAL, BOOLEAN);
DROP FUNCTION @[email protected]_single_range_partition(REGCLASS, ANYELEMENT, ANYELEMENT, TEXT);
DROP FUNCTION @[email protected]_range_partition(REGCLASS, ANYELEMENT, TEXT, OUT ANYARRAY);
DROP FUNCTION @[email protected]_range_partitions(REGCLASS, REGCLASS);
DROP FUNCTION @[email protected]_range_partition(REGCLASS, TEXT);
DROP FUNCTION @[email protected]_partition_internal(REGCLASS, TEXT, TEXT, ANYARRAY, TEXT);
DROP FUNCTION @[email protected]_range_partition(REGCLASS, TEXT);
DROP FUNCTION @[email protected]_partition_internal(REGCLASS, TEXT, TEXT, ANYARRAY, TEXT);
DROP FUNCTION @[email protected]_range_partition(REGCLASS, ANYELEMENT, ANYELEMENT, TEXT);
DROP FUNCTION @[email protected]_range_partition(REGCLASS);
DROP FUNCTION @[email protected]_range_partition(REGCLASS, REGCLASS, ANYELEMENT, ANYELEMENT);
DROP FUNCTION @[email protected]_range_partition(REGCLASS);
DROP FUNCTION @[email protected]_range_condition(TEXT, ANYELEMENT, ANYELEMENT);
DROP FUNCTION @[email protected]_range_by_idx(REGCLASS, INTEGER, ANYELEMENT);
DROP FUNCTION @[email protected]_range_by_part_oid(REGCLASS, REGCLASS, ANYELEMENT);
DROP FUNCTION @[email protected]_min_range_value(REGCLASS, ANYELEMENT);
DROP FUNCTION @[email protected]_max_range_value(REGCLASS, ANYELEMENT);
/* ------------------------------------------------------------------------
* Alter functions' modifiers
* ----------------------------------------------------------------------*/
ALTER FUNCTION @[email protected]_count(REGCLASS) STRICT;
ALTER FUNCTION @[email protected]_data(REGCLASS, OUT BIGINT) STRICT;
ALTER FUNCTION @[email protected]_pathman_for(REGCLASS) STRICT;
ALTER FUNCTION @[email protected]_plain_schema_and_relname(REGCLASS, OUT TEXT, OUT TEXT) STRICT;
ALTER FUNCTION @[email protected]_schema_qualified_name(REGCLASS, TEXT, TEXT) STRICT;
ALTER FUNCTION @[email protected]_triggers(REGCLASS) STRICT;
ALTER FUNCTION @[email protected]_overlap(REGCLASS, ANYELEMENT, ANYELEMENT) CALLED ON NULL INPUT;
ALTER FUNCTION @[email protected]_or_create_range_partition(REGCLASS, ANYELEMENT) CALLED ON NULL INPUT;
/* ------------------------------------------------------------------------
* Add new views
* ----------------------------------------------------------------------*/
CREATE OR REPLACE FUNCTION @[email protected]_partition_list()
RETURNS TABLE (
parent REGCLASS,
partition REGCLASS,
parttype INT4,
partattr TEXT,
range_min TEXT,
range_max TEXT)
AS 'pg_pathman', 'show_partition_list_internal' LANGUAGE C STRICT;
CREATE OR REPLACE VIEW @[email protected]_partition_list
AS SELECT * FROM @[email protected]_partition_list();
GRANT SELECT ON @[email protected]_partition_list TO PUBLIC;
/* ------------------------------------------------------------------------
* (Re)create functions
* ----------------------------------------------------------------------*/
CREATE OR REPLACE FUNCTION @[email protected]_set_param(
relation REGCLASS,
param TEXT,
value ANYELEMENT)
RETURNS VOID AS
$$
BEGIN
EXECUTE format('INSERT INTO @[email protected]_config_params
(partrel, %1$s) VALUES ($1, $2)
ON CONFLICT (partrel) DO UPDATE SET %1$s = $2', param)
USING relation, value;
END
$$
LANGUAGE plpgsql;
CREATE OR REPLACE FUNCTION @[email protected]_enable_parent(
relation REGCLASS,
value BOOLEAN)
RETURNS VOID AS
$$
BEGIN
PERFORM @[email protected]_set_param(relation, 'enable_parent', value);
END
$$
LANGUAGE plpgsql STRICT;
/*
* Partition table using ConcurrentPartWorker.
*/
CREATE OR REPLACE FUNCTION @[email protected]_table_concurrently(
relation REGCLASS,
batch_size INTEGER DEFAULT 1000,
sleep_time FLOAT8 DEFAULT 1.0)
RETURNS VOID AS 'pg_pathman', 'partition_table_concurrently'
LANGUAGE C STRICT;
/*
* Copy rows to partitions concurrently.
*/
CREATE OR REPLACE FUNCTION @extschema@._partition_data_concurrent(
relation REGCLASS,
p_min ANYELEMENT DEFAULT NULL::text,
p_max ANYELEMENT DEFAULT NULL::text,
p_limit INT DEFAULT NULL,
OUT p_total BIGINT)
AS
$$
DECLARE
v_attr TEXT;
v_limit_clause TEXT := '';
v_where_clause TEXT := '';
ctids TID[];
BEGIN
SELECT attname INTO v_attr
FROM @[email protected]_config WHERE partrel = relation;
p_total := 0;
/* Format LIMIT clause if needed */
IF NOT p_limit IS NULL THEN
v_limit_clause := format('LIMIT %s', p_limit);
END IF;
/* Format WHERE clause if needed */
IF NOT p_min IS NULL THEN
v_where_clause := format('%1$s >= $1', v_attr);
END IF;
IF NOT p_max IS NULL THEN
IF NOT p_min IS NULL THEN
v_where_clause := v_where_clause || ' AND ';
END IF;
v_where_clause := v_where_clause || format('%1$s < $2', v_attr);
END IF;
IF v_where_clause != '' THEN
v_where_clause := 'WHERE ' || v_where_clause;
END IF;
/* Lock rows and copy data */
RAISE NOTICE 'Copying data to partitions...';
EXECUTE format('SELECT array(SELECT ctid FROM ONLY %1$s %2$s %3$s FOR UPDATE NOWAIT)',
relation, v_where_clause, v_limit_clause)
USING p_min, p_max
INTO ctids;
EXECUTE format('
WITH data AS (
DELETE FROM ONLY %1$s WHERE ctid = ANY($1) RETURNING *)
INSERT INTO %1$s SELECT * FROM data',
relation)
USING ctids;
/* Get number of inserted rows */
GET DIAGNOSTICS p_total = ROW_COUNT;
RETURN;
END
$$
LANGUAGE plpgsql
SET pg_pathman.enable_partitionfilter = on; /* ensures that PartitionFilter is ON */
/*
* Aggregates several common relation checks before partitioning.
* Suitable for every partitioning type.
*/
CREATE OR REPLACE FUNCTION @[email protected]_relation_checks(
relation REGCLASS,
p_attribute TEXT)
RETURNS BOOLEAN AS
$$
DECLARE
v_rec RECORD;
is_referenced BOOLEAN;
rel_persistence CHAR;
BEGIN
/* Ignore temporary tables */
SELECT relpersistence FROM pg_catalog.pg_class
WHERE oid = relation INTO rel_persistence;
IF rel_persistence = 't'::CHAR THEN
RAISE EXCEPTION 'temporary table "%" cannot be partitioned',
relation::TEXT;
END IF;
IF EXISTS (SELECT * FROM @[email protected]_config
WHERE partrel = relation) THEN
RAISE EXCEPTION 'relation "%" has already been partitioned', relation;
END IF;
IF @[email protected]_attribute_nullable(relation, p_attribute) THEN
RAISE EXCEPTION 'partitioning key ''%'' must be NOT NULL', p_attribute;
END IF;
/* Check if there are foreign keys that reference the relation */
FOR v_rec IN (SELECT * FROM pg_catalog.pg_constraint
WHERE confrelid = relation::REGCLASS::OID)
LOOP
is_referenced := TRUE;
RAISE WARNING 'foreign key "%" references relation "%"',
v_rec.conname, relation;
END LOOP;
IF is_referenced THEN
RAISE EXCEPTION 'relation "%" is referenced from other relations', relation;
END IF;
RETURN TRUE;
END
$$
LANGUAGE plpgsql;
/*
* DDL trigger that removes entry from pathman_config table.
*/
CREATE OR REPLACE FUNCTION @[email protected]_ddl_trigger_func()
RETURNS event_trigger AS
$$
DECLARE
obj record;
pg_class_oid oid;
relids regclass[];
BEGIN
pg_class_oid = 'pg_catalog.pg_class'::regclass;
/* Find relids to remove from config */
SELECT array_agg(cfg.partrel) INTO relids
FROM pg_event_trigger_dropped_objects() AS events
JOIN @[email protected]_config AS cfg ON cfg.partrel::oid = events.objid
WHERE events.classid = pg_class_oid;
/* Cleanup pathman_config */
DELETE FROM @[email protected]_config WHERE partrel = ANY(relids);
/* Cleanup params table too */
DELETE FROM @[email protected]_config_params WHERE partrel = ANY(relids);
END
$$
LANGUAGE plpgsql;
/*
* Drop partitions. If delete_data set to TRUE, partitions
* will be dropped with all the data.
*/
CREATE OR REPLACE FUNCTION @[email protected]_partitions(
parent_relid REGCLASS,
delete_data BOOLEAN DEFAULT FALSE)
RETURNS INTEGER AS
$$
DECLARE
v_rec RECORD;
v_rows BIGINT;
v_part_count INTEGER := 0;
conf_num_del INTEGER;
v_relkind CHAR;
BEGIN
PERFORM @[email protected]_relname(parent_relid);
/* Drop trigger first */
PERFORM @[email protected]_triggers(parent_relid);
WITH config_num_deleted AS (DELETE FROM @[email protected]_config
WHERE partrel = parent_relid
RETURNING *)
SELECT count(*) from config_num_deleted INTO conf_num_del;
DELETE FROM @[email protected]_config_params WHERE partrel = parent_relid;
IF conf_num_del = 0 THEN
RAISE EXCEPTION 'relation "%" has no partitions', parent_relid::TEXT;
END IF;
FOR v_rec IN (SELECT inhrelid::REGCLASS AS tbl
FROM pg_catalog.pg_inherits
WHERE inhparent::regclass = parent_relid
ORDER BY inhrelid ASC)
LOOP
IF NOT delete_data THEN
EXECUTE format('INSERT INTO %s SELECT * FROM %s',
parent_relid::TEXT,
v_rec.tbl::TEXT);
GET DIAGNOSTICS v_rows = ROW_COUNT;
/* Show number of copied rows */
RAISE NOTICE '% rows copied from %', v_rows, v_rec.tbl::TEXT;
END IF;
SELECT relkind FROM pg_catalog.pg_class
WHERE oid = v_rec.tbl
INTO v_relkind;
/*
* Determine the kind of child relation. It can be either regular
* table (r) or foreign table (f). Depending on relkind we use
* DROP TABLE or DROP FOREIGN TABLE.
*/
IF v_relkind = 'f' THEN
EXECUTE format('DROP FOREIGN TABLE %s', v_rec.tbl::TEXT);
ELSE
EXECUTE format('DROP TABLE %s', v_rec.tbl::TEXT);
END IF;
v_part_count := v_part_count + 1;
END LOOP;
/* Notify backend about changes */
PERFORM @[email protected]_remove_partitions(parent_relid);
RETURN v_part_count;
END
$$ LANGUAGE plpgsql
SET pg_pathman.enable_partitionfilter = off; /* ensures that PartitionFilter is OFF */
/*
* Copy all of parent's foreign keys.
*/
CREATE OR REPLACE FUNCTION @[email protected]_foreign_keys(
parent_relid REGCLASS,
partition REGCLASS)
RETURNS VOID AS
$$
DECLARE
rec RECORD;
BEGIN
PERFORM @[email protected]_relname(parent_relid);
PERFORM @[email protected]_relname(partition);
FOR rec IN (SELECT oid as conid FROM pg_catalog.pg_constraint
WHERE conrelid = parent_relid AND contype = 'f')
LOOP
EXECUTE format('ALTER TABLE %s ADD %s',
partition::TEXT,
pg_catalog.pg_get_constraintdef(rec.conid));
END LOOP;
END
$$ LANGUAGE plpgsql STRICT;
/*
* Extract basic type of a domain.
*/
CREATE OR REPLACE FUNCTION @[email protected]_base_type(REGTYPE)
RETURNS REGTYPE AS 'pg_pathman', 'get_base_type_pl'
LANGUAGE C STRICT;
/*
* Returns attribute type name for relation.
*/
CREATE OR REPLACE FUNCTION @[email protected]_attribute_type(
REGCLASS, TEXT)
RETURNS REGTYPE AS 'pg_pathman', 'get_attribute_type_pl'
LANGUAGE C STRICT;
/*
* Return tablespace name for specified relation.
*/
CREATE OR REPLACE FUNCTION @[email protected]_rel_tablespace_name(REGCLASS)
RETURNS TEXT AS 'pg_pathman', 'get_rel_tablespace_name'
LANGUAGE C STRICT;
/*
* Checks that callback function meets specific requirements. Particularly it
* must have the only JSONB argument and VOID return type.
*/
CREATE OR REPLACE FUNCTION @[email protected]_on_partition_created_callback(
callback REGPROC)
RETURNS VOID AS 'pg_pathman', 'validate_on_part_init_callback_pl'
LANGUAGE C STRICT;
/*
* Invoke init_callback on RANGE partition.
*/
CREATE OR REPLACE FUNCTION @[email protected]_on_partition_created_callback(
parent_relid REGCLASS,
partition REGCLASS,
init_callback REGPROCEDURE,
start_value ANYELEMENT,
end_value ANYELEMENT)
RETURNS VOID AS 'pg_pathman', 'invoke_on_partition_created_callback'
LANGUAGE C;
/*
* Invoke init_callback on HASH partition.
*/
CREATE OR REPLACE FUNCTION @[email protected]_on_partition_created_callback(
parent_relid REGCLASS,
partition REGCLASS,
init_callback REGPROCEDURE)
RETURNS VOID AS 'pg_pathman', 'invoke_on_partition_created_callback'
LANGUAGE C;
/*
* Creates hash partitions for specified relation
*/
CREATE OR REPLACE FUNCTION @[email protected]_hash_partitions(
parent_relid REGCLASS,
attribute TEXT,
partitions_count INTEGER,
partition_data BOOLEAN DEFAULT TRUE)
RETURNS INTEGER AS
$$
DECLARE
v_child_relname TEXT;
v_plain_schema TEXT;
v_plain_relname TEXT;
v_atttype REGTYPE;
v_hashfunc REGPROC;
v_init_callback REGPROCEDURE;
BEGIN
PERFORM @[email protected]_relname(parent_relid);
IF partition_data = true THEN
/* Acquire data modification lock */
PERFORM @[email protected]_relation_modification(parent_relid);
ELSE
/* Acquire lock on parent */
PERFORM @[email protected]_partitioned_relation(parent_relid);
END IF;
attribute := lower(attribute);
PERFORM @[email protected]_relation_checks(parent_relid, attribute);
/* Fetch atttype and its hash function */
v_atttype := @[email protected]_attribute_type(parent_relid, attribute);
v_hashfunc := @[email protected]_type_hash_func(v_atttype);
SELECT * INTO v_plain_schema, v_plain_relname
FROM @[email protected]_plain_schema_and_relname(parent_relid);
/* Insert new entry to pathman config */
INSERT INTO @[email protected]_config (partrel, attname, parttype)
VALUES (parent_relid, attribute, 1);
/* Create partitions and update pg_pathman configuration */
FOR partnum IN 0..partitions_count-1
LOOP
v_child_relname := format('%s.%s',
quote_ident(v_plain_schema),
quote_ident(v_plain_relname || '_' || partnum));
EXECUTE format(
'CREATE TABLE %1$s (LIKE %2$s INCLUDING ALL) INHERITS (%2$s) TABLESPACE %s',
v_child_relname,
parent_relid::TEXT,
@[email protected]_rel_tablespace_name(parent_relid));
EXECUTE format('ALTER TABLE %s ADD CONSTRAINT %s
CHECK (@[email protected]_hash_part_idx(%s(%s), %s) = %s)',
v_child_relname,
@[email protected]_check_constraint_name(v_child_relname::REGCLASS,
attribute),
v_hashfunc::TEXT,
attribute,
partitions_count,
partnum);
PERFORM @[email protected]_foreign_keys(parent_relid, v_child_relname::REGCLASS);
/* Fetch init_callback from 'params' table */
WITH stub_callback(stub) as (values (0))
SELECT coalesce(init_callback, 0::REGPROCEDURE)
FROM stub_callback
LEFT JOIN @[email protected]_config_params AS params
ON params.partrel = parent_relid
INTO v_init_callback;
PERFORM @[email protected]_on_partition_created_callback(parent_relid,
v_child_relname::REGCLASS,
v_init_callback);
END LOOP;
/* Notify backend about changes */
PERFORM @[email protected]_create_partitions(parent_relid);
/* Copy data */
IF partition_data = true THEN
PERFORM @[email protected]_enable_parent(parent_relid, false);
PERFORM @[email protected]_data(parent_relid);
ELSE
PERFORM @[email protected]_enable_parent(parent_relid, true);
END IF;
RETURN partitions_count;
END
$$ LANGUAGE plpgsql
SET client_min_messages = WARNING;
/*
* Creates an update trigger
*/
CREATE OR REPLACE FUNCTION @[email protected]_hash_update_trigger(
parent_relid REGCLASS)
RETURNS TEXT AS
$$
DECLARE
func TEXT := 'CREATE OR REPLACE FUNCTION %1$s()
RETURNS TRIGGER AS
$body$
DECLARE
old_idx INTEGER; /* partition indices */
new_idx INTEGER;
BEGIN
old_idx := @[email protected]_hash_part_idx(%9$s(OLD.%2$s), %3$s);
new_idx := @[email protected]_hash_part_idx(%9$s(NEW.%2$s), %3$s);
IF old_idx = new_idx THEN
RETURN NEW;
END IF;
EXECUTE format(''DELETE FROM %8$s WHERE %4$s'', old_idx)
USING %5$s;
EXECUTE format(''INSERT INTO %8$s VALUES (%6$s)'', new_idx)
USING %7$s;
RETURN NULL;
END $body$
LANGUAGE plpgsql';
trigger TEXT := 'CREATE TRIGGER %s
BEFORE UPDATE ON %s
FOR EACH ROW EXECUTE PROCEDURE %s()';
att_names TEXT;
old_fields TEXT;
new_fields TEXT;
att_val_fmt TEXT;
att_fmt TEXT;
attr TEXT;
plain_schema TEXT;
plain_relname TEXT;
child_relname_format TEXT;
funcname TEXT;
triggername TEXT;
atttype REGTYPE;
partitions_count INTEGER;
BEGIN
attr := attname FROM @[email protected]_config WHERE partrel = parent_relid;
IF attr IS NULL THEN
RAISE EXCEPTION 'table "%" is not partitioned', parent_relid::TEXT;
END IF;
SELECT string_agg(attname, ', '),
string_agg('OLD.' || attname, ', '),
string_agg('NEW.' || attname, ', '),
string_agg('CASE WHEN NOT $' || attnum || ' IS NULL THEN ' ||
attname || ' = $' || attnum || ' ' ||
'ELSE ' ||
attname || ' IS NULL END',
' AND '),
string_agg('$' || attnum, ', ')
FROM pg_catalog.pg_attribute
WHERE attrelid = parent_relid AND attnum > 0
INTO att_names,
old_fields,
new_fields,
att_val_fmt,
att_fmt;
partitions_count := COUNT(*) FROM pg_catalog.pg_inherits
WHERE inhparent = parent_relid::oid;
/* Build trigger & trigger function's names */
funcname := @[email protected]_update_trigger_func_name(parent_relid);
triggername := @[email protected]_update_trigger_name(parent_relid);
/* Build partition name template */
SELECT * INTO plain_schema, plain_relname
FROM @[email protected]_plain_schema_and_relname(parent_relid);
child_relname_format := quote_ident(plain_schema) || '.' ||
quote_ident(plain_relname || '_%s');
/* Fetch base hash function for atttype */
atttype := @[email protected]_attribute_type(parent_relid, attr);
/* Format function definition and execute it */
EXECUTE format(func, funcname, attr, partitions_count, att_val_fmt,
old_fields, att_fmt, new_fields, child_relname_format,
@[email protected]_type_hash_func(atttype)::TEXT);
/* Create trigger on every partition */
FOR num IN 0..partitions_count-1
LOOP
EXECUTE format(trigger,
triggername,
format(child_relname_format, num),
funcname);
END LOOP;
return funcname;
END
$$ LANGUAGE plpgsql;
/*
* Returns hash function OID for specified type
*/
CREATE OR REPLACE FUNCTION @[email protected]_type_hash_func(REGTYPE)
RETURNS REGPROC AS 'pg_pathman', 'get_type_hash_func'
LANGUAGE C STRICT;
/*
* Check RANGE partition boundaries.
*/
CREATE OR REPLACE FUNCTION @[email protected]_boundaries(
parent_relid REGCLASS,
attribute TEXT,
start_value ANYELEMENT,
end_value ANYELEMENT)
RETURNS VOID AS
$$
DECLARE
v_min start_value%TYPE;
v_max start_value%TYPE;
v_count BIGINT;
BEGIN
/* Get min and max values */
EXECUTE format('SELECT count(*), min(%1$s), max(%1$s)
FROM %2$s WHERE NOT %1$s IS NULL',
attribute, parent_relid::TEXT)
INTO v_count, v_min, v_max;
/* Check if column has NULL values */
IF v_count > 0 AND (v_min IS NULL OR v_max IS NULL) THEN
RAISE EXCEPTION '''%'' column contains NULL values', attribute;
END IF;
/* Check lower boundary */
IF start_value > v_min THEN
RAISE EXCEPTION 'start value is less than minimum value of ''%''',
attribute;
END IF;
/* Check upper boundary */
IF end_value <= v_max THEN
RAISE EXCEPTION 'not enough partitions to fit all values of ''%''',
attribute;
END IF;
END
$$ LANGUAGE plpgsql;
/*
* Creates RANGE partitions for specified relation based on datetime attribute
*/
CREATE OR REPLACE FUNCTION @[email protected]_range_partitions(
parent_relid REGCLASS,
attribute TEXT,
start_value ANYELEMENT,
p_interval INTERVAL,
p_count INTEGER DEFAULT NULL,
partition_data BOOLEAN DEFAULT TRUE)
RETURNS INTEGER AS
$$
DECLARE
v_rows_count BIGINT;
v_atttype REGTYPE;
v_max start_value%TYPE;
v_cur_value start_value%TYPE := start_value;
end_value start_value%TYPE;
i INTEGER;
BEGIN
PERFORM @[email protected]_relname(parent_relid);
IF partition_data = true THEN
/* Acquire data modification lock */
PERFORM @[email protected]_relation_modification(parent_relid);
ELSE
/* Acquire lock on parent */
PERFORM @[email protected]_partitioned_relation(parent_relid);
END IF;
attribute := lower(attribute);
PERFORM @[email protected]_relation_checks(parent_relid, attribute);
IF p_count < 0 THEN
RAISE EXCEPTION '''p_count'' must not be less than 0';
END IF;
/* Try to determine partitions count if not set */
IF p_count IS NULL THEN
EXECUTE format('SELECT count(*), max(%s) FROM %s', attribute, parent_relid)
INTO v_rows_count, v_max;
IF v_rows_count = 0 THEN
RAISE EXCEPTION 'cannot determine partitions count for empty table';
END IF;
p_count := 0;
WHILE v_cur_value <= v_max
LOOP
v_cur_value := v_cur_value + p_interval;
p_count := p_count + 1;
END LOOP;
END IF;
v_atttype := @[email protected]_base_type(pg_typeof(start_value));
/*
* In case when user doesn't want to automatically create partitions
* and specifies partition count as 0 then do not check boundaries
*/
IF p_count != 0 THEN
/* compute right bound of partitioning through additions */
end_value := start_value;
FOR i IN 1..p_count
LOOP
end_value := end_value + p_interval;
END LOOP;
/* Check boundaries */
EXECUTE format('SELECT @[email protected]_boundaries(''%s'', ''%s'', ''%s'', ''%s''::%s)',
parent_relid,
attribute,
start_value,
end_value,
v_atttype::TEXT);
END IF;
/* Create sequence for child partitions names */
PERFORM @[email protected]_or_replace_sequence(schema, relname)
FROM @[email protected]_plain_schema_and_relname(parent_relid);
/* Insert new entry to pathman config */
INSERT INTO @[email protected]_config (partrel, attname, parttype, range_interval)
VALUES (parent_relid, attribute, 2, p_interval::TEXT);
/* Create first partition */
FOR i IN 1..p_count
LOOP
EXECUTE
format('SELECT @[email protected]_single_range_partition($1, $2, $3::%s, tablespace:=$4)',
v_atttype::TEXT)
USING
parent_relid,
start_value,
start_value + p_interval,
@[email protected]_rel_tablespace_name(parent_relid);
start_value := start_value + p_interval;
END LOOP;
/* Notify backend about changes */
PERFORM @[email protected]_create_partitions(parent_relid);
/* Relocate data if asked to */
IF partition_data = true THEN
PERFORM @[email protected]_enable_parent(parent_relid, false);
PERFORM @[email protected]_data(parent_relid);
ELSE
PERFORM @[email protected]_enable_parent(parent_relid, true);
END IF;
RETURN p_count;
END
$$ LANGUAGE plpgsql;
/*
* Creates RANGE partitions for specified relation based on numerical attribute
*/
CREATE OR REPLACE FUNCTION @[email protected]_range_partitions(
parent_relid REGCLASS,
attribute TEXT,
start_value ANYELEMENT,
p_interval ANYELEMENT,
p_count INTEGER DEFAULT NULL,
partition_data BOOLEAN DEFAULT TRUE)
RETURNS INTEGER AS
$$
DECLARE
v_rows_count BIGINT;
v_max start_value%TYPE;
v_cur_value start_value%TYPE := start_value;
end_value start_value%TYPE;
i INTEGER;
BEGIN
PERFORM @[email protected]_relname(parent_relid);
IF partition_data = true THEN
/* Acquire data modification lock */
PERFORM @[email protected]_relation_modification(parent_relid);
ELSE
/* Acquire lock on parent */
PERFORM @[email protected]_partitioned_relation(parent_relid);
END IF;
attribute := lower(attribute);
PERFORM @[email protected]_relation_checks(parent_relid, attribute);
IF p_count < 0 THEN
RAISE EXCEPTION 'partitions count must not be less than zero';
END IF;
/* Try to determine partitions count if not set */
IF p_count IS NULL THEN
EXECUTE format('SELECT count(*), max(%s) FROM %s', attribute, parent_relid)
INTO v_rows_count, v_max;
IF v_rows_count = 0 THEN
RAISE EXCEPTION 'cannot determine partitions count for empty table';
END IF;
IF v_max IS NULL THEN
RAISE EXCEPTION '''%'' column has NULL values', attribute;
END IF;
p_count := 0;
WHILE v_cur_value <= v_max
LOOP
v_cur_value := v_cur_value + p_interval;
p_count := p_count + 1;
END LOOP;
END IF;
/*
* In case when user doesn't want to automatically create partitions
* and specifies partition count as 0 then do not check boundaries
*/
IF p_count != 0 THEN
/* compute right bound of partitioning through additions */
end_value := start_value;
FOR i IN 1..p_count
LOOP
end_value := end_value + p_interval;
END LOOP;
/* check boundaries */
PERFORM @[email protected]_boundaries(parent_relid,
attribute,
start_value,
end_value);
END IF;
/* Create sequence for child partitions names */
PERFORM @[email protected]_or_replace_sequence(schema, relname)
FROM @[email protected]_plain_schema_and_relname(parent_relid);
/* Insert new entry to pathman config */
INSERT INTO @[email protected]_config (partrel, attname, parttype, range_interval)
VALUES (parent_relid, attribute, 2, p_interval::TEXT);
/* create first partition */
FOR i IN 1..p_count
LOOP
PERFORM @[email protected]_single_range_partition(
parent_relid,
start_value,
start_value + p_interval,
tablespace := @[email protected]_rel_tablespace_name(parent_relid));
start_value := start_value + p_interval;
END LOOP;
/* Notify backend about changes */
PERFORM @[email protected]_create_partitions(parent_relid);
/* Relocate data if asked to */
IF partition_data = true THEN
PERFORM @[email protected]_enable_parent(parent_relid, false);
PERFORM @[email protected]_data(parent_relid);
ELSE
PERFORM @[email protected]_enable_parent(parent_relid, true);
END IF;
RETURN p_count;
END
$$ LANGUAGE plpgsql;
/*
* Creates RANGE partitions for specified range
*/
CREATE OR REPLACE FUNCTION @[email protected]_partitions_from_range(
parent_relid REGCLASS,
attribute TEXT,
start_value ANYELEMENT,
end_value ANYELEMENT,
p_interval ANYELEMENT,
partition_data BOOLEAN DEFAULT TRUE)
RETURNS INTEGER AS
$$
DECLARE
part_count INTEGER := 0;
BEGIN
PERFORM @[email protected]_relname(parent_relid);
IF partition_data = true THEN
/* Acquire data modification lock */
PERFORM @[email protected]_relation_modification(parent_relid);
ELSE
/* Acquire lock on parent */
PERFORM @[email protected]_partitioned_relation(parent_relid);
END IF;
attribute := lower(attribute);
PERFORM @[email protected]_relation_checks(parent_relid, attribute);
IF p_interval <= 0 THEN
RAISE EXCEPTION 'interval must be positive';
END IF;
/* Check boundaries */
PERFORM @[email protected]_boundaries(parent_relid,
attribute,
start_value,
end_value);
/* Create sequence for child partitions names */
PERFORM @[email protected]_or_replace_sequence(schema, relname)
FROM @[email protected]_plain_schema_and_relname(parent_relid);
/* Insert new entry to pathman config */
INSERT INTO @[email protected]_config (partrel, attname, parttype, range_interval)
VALUES (parent_relid, attribute, 2, p_interval::TEXT);
WHILE start_value <= end_value
LOOP
PERFORM @[email protected]_single_range_partition(
parent_relid,
start_value,
start_value + p_interval,
tablespace := @[email protected]_rel_tablespace_name(parent_relid));
start_value := start_value + p_interval;
part_count := part_count + 1;
END LOOP;
/* Notify backend about changes */
PERFORM @[email protected]_create_partitions(parent_relid);
/* Relocate data if asked to */
IF partition_data = true THEN
PERFORM @[email protected]_enable_parent(parent_relid, false);
PERFORM @[email protected]_data(parent_relid);
ELSE