-
Notifications
You must be signed in to change notification settings - Fork 1
/
sql.go
4532 lines (4050 loc) · 191 KB
/
sql.go
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
/**
* Here be dragons. Don't look in here.
*
* This file contains all the SQL to load into Postgres all of the functions needed.
* These are pulled from: https://github.com/keithf4/pg_partman/tree/master/sql/functions
*
* Things known:
* - Updates are manual (and the SQL isn't exactly verbatim so it can work with Amazon RDS)
* - This file is long, but including the SQL here (opposed to external SQL files) means the SQL gets built into the binary making things easier
*/
package main
import (
"log"
)
// Checks if the partition management schema exist in the database.
func (db DB) sqlFunctionsExist() bool {
var count int
err := db.Get(&count, "SELECT COUNT(schema_name) FROM information_schema.schemata WHERE schema_name = 'partman';")
if err != nil {
log.Printf("%v", err)
return false
}
// SELECT count(*) FROM pg_proc WHERE proname = 'create_parent';
return count > 0
}
// Loads pg_partman functions, types, schema, etc. Call this for each database.
func (db DB) loadPgPartman() {
// Everything is going under a partman schema.
_, err := db.Exec("CREATE SCHEMA IF NOT EXISTS partman;")
if err != nil {
log.Printf("%v", err)
}
db.loadSqlTables()
db.loadSqlTypes()
db.loadSqlFunctions()
}
// Removes the partman schema including all objects.
func (db DB) unloadPartman() {
_, err := db.Exec("DROP SCHEMA IF EXISTS partman CASCADE;")
if err != nil {
log.Printf("%v", err)
}
}
// Loads types
func (db DB) loadSqlTypes() {
_, err := db.Exec(`
CREATE TYPE partman.check_parent_table AS (parent_table text, count bigint);
`)
if err != nil {
log.Printf("%v", err)
}
}
// Loads functions from pg_partman
func (db DB) loadSqlFunctions() {
var err error
tx, err := db.Begin()
if err != nil {
log.Printf("%v", err)
return
}
// apply_constraints()
_, err = tx.Exec(`
/*
* Apply constraints managed by partman extension
*/
CREATE FUNCTION partman.apply_constraints(p_parent_table text, p_child_table text DEFAULT NULL, p_analyze boolean DEFAULT TRUE, p_debug boolean DEFAULT FALSE) RETURNS void
LANGUAGE plpgsql
AS $$
DECLARE
v_child_table text;
v_child_tablename text;
v_col text;
v_constraint_cols text[];
v_constraint_col_type text;
v_constraint_name text;
v_datetime_string text;
v_existing_constraint_name text;
v_job_id bigint;
v_jobmon boolean;
v_jobmon_schema text;
v_last_partition text;
v_last_partition_id int;
v_last_partition_timestamp timestamp;
v_constraint_values record;
v_old_search_path text;
v_parent_schema text;
v_parent_tablename text;
v_part_interval text;
v_partition_suffix text;
v_premake int;
v_sql text;
v_step_id bigint;
v_suffix_position int;
v_type text;
BEGIN
SELECT type
, part_interval
, premake
, datetime_string
, constraint_cols
, jobmon
INTO v_type
, v_part_interval
, v_premake
, v_datetime_string
, v_constraint_cols
, v_jobmon
FROM partman.part_config
WHERE parent_table = p_parent_table;
IF v_constraint_cols IS NULL THEN
IF p_debug THEN
RAISE NOTICE 'Given parent table (%) not set up for constraint management (constraint_cols is NULL)', p_parent_table;
END IF;
-- Returns silently to allow this function to be simply called by maintenance processes without having to check if config options are set.
RETURN;
END IF;
SELECT show_partitions INTO v_last_partition FROM partman.show_partitions(p_parent_table, 'DESC') LIMIT 1;
IF v_jobmon THEN
SELECT nspname INTO v_jobmon_schema FROM pg_catalog.pg_namespace n, pg_catalog.pg_extension e WHERE e.extname = 'pg_jobmon' AND e.extnamespace = n.oid;
IF v_jobmon_schema IS NOT NULL THEN
SELECT current_setting('search_path') INTO v_old_search_path;
EXECUTE 'SELECT set_config(''search_path'',''partman,'||v_jobmon_schema||''',''false'')';
END IF;
END IF;
IF v_jobmon_schema IS NOT NULL THEN
v_job_id := add_job('PARTMAN CREATE CONSTRAINT: '||p_parent_table);
END IF;
SELECT schemaname, tablename INTO v_parent_schema, v_parent_tablename FROM pg_tables WHERE schemaname ||'.'|| tablename = p_parent_table;
-- If p_child_table is null, figure out the partition that is the one right before the premake value backwards.
IF p_child_table IS NULL THEN
IF v_jobmon_schema IS NOT NULL THEN
v_step_id := add_step(v_job_id, 'Automatically determining most recent child on which to apply constraints');
END IF;
v_suffix_position := (length(v_last_partition) - position('p_' in reverse(v_last_partition))) + 2;
IF v_type IN ('time-static', 'time-dynamic') THEN
v_last_partition_timestamp := to_timestamp(substring(v_last_partition from v_suffix_position), v_datetime_string);
v_partition_suffix := to_char(v_last_partition_timestamp - (v_part_interval::interval * ((v_premake * 2)+1) ), v_datetime_string);
ELSIF v_type IN ('id-static', 'id-dynamic') THEN
v_last_partition_id := substring(v_last_partition from v_suffix_position)::int;
v_partition_suffix := (v_last_partition_id - (v_part_interval::int * ((v_premake * 2)+1) ))::text;
END IF;
v_child_table := partman.check_name_length(v_parent_tablename, v_parent_schema, v_partition_suffix, TRUE);
IF v_jobmon_schema IS NOT NULL THEN
PERFORM update_step(v_step_id, 'OK', 'Target child table: '||v_child_table);
END IF;
ELSE
v_child_table := p_child_table;
END IF;
IF v_jobmon_schema IS NOT NULL THEN
v_step_id := add_step(v_job_id, 'Checking if target child table exists');
END IF;
SELECT tablename INTO v_child_tablename FROM pg_catalog.pg_tables WHERE schemaname ||'.'|| tablename = v_child_table;
IF v_child_tablename IS NULL THEN
IF v_jobmon_schema IS NOT NULL THEN
PERFORM update_step(v_step_id, 'NOTICE', 'Target child table ('||v_child_table||') does not exist. Skipping constraint creation.');
PERFORM close_job(v_job_id);
EXECUTE 'SELECT set_config(''search_path'','''||v_old_search_path||''',''false'')';
END IF;
IF p_debug THEN
RAISE NOTICE 'Target child table (%) does not exist. Skipping constraint creation.', v_child_table;
END IF;
RETURN;
ELSE
IF v_jobmon_schema IS NOT NULL THEN
PERFORM update_step(v_step_id, 'OK', 'Done');
END IF;
END IF;
FOREACH v_col IN ARRAY v_constraint_cols
LOOP
SELECT c.conname
INTO v_existing_constraint_name
FROM pg_catalog.pg_constraint c
JOIN pg_catalog.pg_attribute a ON c.conrelid = a.attrelid
WHERE conrelid = v_child_table::regclass
AND c.conname LIKE 'partmanconstr_%'
AND c.contype = 'c'
AND a.attname = v_col
AND ARRAY[a.attnum] <@ c.conkey
AND a.attisdropped = false;
IF v_jobmon_schema IS NOT NULL THEN
v_step_id := add_step(v_job_id, 'Applying new constraint on column: '||v_col);
END IF;
IF v_existing_constraint_name IS NOT NULL THEN
IF v_jobmon_schema IS NOT NULL THEN
PERFORM update_step(v_step_id, 'NOTICE', 'Partman managed constraint already exists on this table ('||v_child_table||') and column ('||v_col||'). Skipping creation.');
END IF;
RAISE WARNING 'Partman managed constraint already exists on this table (%) and column (%). Skipping creation.', v_child_table, v_col ;
CONTINUE;
END IF;
-- Ensure column name gets put on end of constraint name to help avoid naming conflicts
v_constraint_name := partman.check_name_length('partmanconstr_'||v_child_tablename, p_suffix := '_'||v_col);
EXECUTE 'SELECT min('||v_col||')::text AS min, max('||v_col||')::text AS max FROM '||v_child_table INTO v_constraint_values;
IF v_constraint_values IS NOT NULL THEN
v_sql := concat('ALTER TABLE ', v_child_table, ' ADD CONSTRAINT ', v_constraint_name
, ' CHECK (', v_col, ' >= ', quote_literal(v_constraint_values.min), ' AND '
, v_col, ' <= ', quote_literal(v_constraint_values.max), ')' );
IF p_debug THEN
RAISE NOTICE 'Constraint creation query: %', v_sql;
END IF;
EXECUTE v_sql;
IF v_jobmon_schema IS NOT NULL THEN
PERFORM update_step(v_step_id, 'OK', 'New constraint created: '||v_sql);
END IF;
ELSE
IF p_debug THEN
RAISE NOTICE 'Given column (%) contains all NULLs. No constraint created', v_col;
END IF;
IF v_jobmon_schema IS NOT NULL THEN
PERFORM update_step(v_step_id, 'NOTICE', 'Given column ('||v_col||') contains all NULLs. No constraint created');
END IF;
END IF;
END LOOP;
IF p_analyze THEN
EXECUTE 'ANALYZE '||p_parent_table;
END IF;
IF v_jobmon_schema IS NOT NULL THEN
PERFORM close_job(v_job_id);
EXECUTE 'SELECT set_config(''search_path'','''||v_old_search_path||''',''false'')';
END IF;
EXCEPTION
WHEN OTHERS THEN
IF v_jobmon_schema IS NOT NULL THEN
IF v_job_id IS NULL THEN
EXECUTE 'SELECT '||v_jobmon_schema||'.add_job(''PARTMAN CREATE CONSTRAINT: '||p_parent_table||''')' INTO v_job_id;
EXECUTE 'SELECT '||v_jobmon_schema||'.add_step('||v_job_id||', ''EXCEPTION before job logging started'')' INTO v_step_id;
ELSIF v_step_id IS NULL THEN
EXECUTE 'SELECT '||v_jobmon_schema||'.add_step('||v_job_id||', ''EXCEPTION before first step logged'')' INTO v_step_id;
END IF;
EXECUTE 'SELECT '||v_jobmon_schema||'.update_step('||v_step_id||', ''CRITICAL'', ''ERROR: '||coalesce(SQLERRM,'unknown')||''')';
EXECUTE 'SELECT '||v_jobmon_schema||'.fail_job('||v_job_id||')';
END IF;
RAISE EXCEPTION '%', SQLERRM;
END
$$;
`)
if err != nil {
log.Printf("%v", err)
}
// apply_foreign_keys
_, err = tx.Exec(`
/*
* Apply foreign keys that exist on the given parent to the given child table
*/
CREATE FUNCTION partman.apply_foreign_keys(p_parent_table text, p_child_table text DEFAULT NULL, p_debug boolean DEFAULT false) RETURNS void
LANGUAGE plpgsql
AS $$
DECLARE
v_job_id bigint;
v_jobmon text;
v_jobmon_schema text;
v_old_search_path text;
v_ref_schema text;
v_ref_table text;
v_row record;
v_schemaname text;
v_sql text;
v_step_id bigint;
v_tablename text;
BEGIN
SELECT jobmon INTO v_jobmon FROM partman.part_config WHERE parent_table = p_parent_table;
IF v_jobmon THEN
SELECT nspname INTO v_jobmon_schema FROM pg_catalog.pg_namespace n, pg_catalog.pg_extension e WHERE e.extname = 'pg_jobmon' AND e.extnamespace = n.oid;
IF v_jobmon_schema IS NOT NULL THEN
SELECT current_setting('search_path') INTO v_old_search_path;
EXECUTE 'SELECT set_config(''search_path'',''partman,'||v_jobmon_schema||''',''false'')';
END IF;
END IF;
IF v_jobmon_schema IS NOT NULL THEN
v_job_id := add_job('PARTMAN APPLYING FOREIGN KEYS: '||p_parent_table);
END IF;
IF v_jobmon_schema IS NOT NULL THEN
v_step_id := add_step(v_job_id, 'Checking if target child table exists');
END IF;
SELECT schemaname, tablename INTO v_schemaname, v_tablename
FROM pg_catalog.pg_tables
WHERE schemaname||'.'||tablename = p_child_table;
IF v_tablename IS NULL THEN
IF v_jobmon_schema IS NOT NULL THEN
PERFORM update_step(v_step_id, 'CRITICAL', 'Target child table ('||v_child_table||') does not exist.');
PERFORM fail_job(v_job_id);
EXECUTE 'SELECT set_config(''search_path'','''||v_old_search_path||''',''false'')';
END IF;
RAISE EXCEPTION 'Target child table (%.%) does not exist.', v_schemaname, v_tablename;
RETURN;
ELSE
IF v_jobmon_schema IS NOT NULL THEN
PERFORM update_step(v_step_id, 'OK', 'Done');
END IF;
END IF;
FOR v_row IN
SELECT n.nspname||'.'||cl.relname AS ref_table
, '"'||string_agg(att.attname, '","')||'"' AS ref_column
, '"'||string_agg(att2.attname, '","')||'"' AS child_column
FROM
( SELECT con.conname
, unnest(con.conkey) as ref
, unnest(con.confkey) as child
, con.confrelid
, con.conrelid
FROM pg_catalog.pg_class c
JOIN pg_catalog.pg_namespace n ON c.relnamespace = n.oid
JOIN pg_catalog.pg_constraint con ON c.oid = con.conrelid
WHERE n.nspname ||'.'|| c.relname = p_parent_table
AND con.contype = 'f'
ORDER BY con.conkey
) keys
JOIN pg_catalog.pg_class cl ON cl.oid = keys.confrelid
JOIN pg_catalog.pg_namespace n ON cl.relnamespace = n.oid
JOIN pg_catalog.pg_attribute att ON att.attrelid = keys.confrelid AND att.attnum = keys.child
JOIN pg_catalog.pg_attribute att2 ON att2.attrelid = keys.conrelid AND att2.attnum = keys.ref
GROUP BY keys.conname, n.nspname, cl.relname
LOOP
SELECT schemaname, tablename INTO v_ref_schema, v_ref_table FROM pg_tables WHERE schemaname||'.'||tablename = v_row.ref_table;
v_sql := format('ALTER TABLE %I.%I ADD FOREIGN KEY (%s) REFERENCES %I.%I (%s)',
v_schemaname, v_tablename, v_row.child_column, v_ref_schema, v_ref_table, v_row.ref_column);
IF v_jobmon_schema IS NOT NULL THEN
v_step_id := add_step(v_job_id, 'Applying FK: '||v_sql);
END IF;
EXECUTE v_sql;
IF v_jobmon_schema IS NOT NULL THEN
PERFORM update_step(v_step_id, 'OK', 'FK applied');
END IF;
END LOOP;
IF v_jobmon_schema IS NOT NULL THEN
PERFORM close_job(v_job_id);
EXECUTE 'SELECT set_config(''search_path'','''||v_old_search_path||''',''false'')';
END IF;
EXCEPTION
WHEN OTHERS THEN
IF v_jobmon_schema IS NOT NULL THEN
IF v_job_id IS NULL THEN
EXECUTE 'SELECT '||v_jobmon_schema||'.add_job(''PARTMAN APPLYING FOREIGN KEYS: '||p_parent_table||''')' INTO v_job_id;
EXECUTE 'SELECT '||v_jobmon_schema||'.add_step('||v_job_id||', ''EXCEPTION before job logging started'')' INTO v_step_id;
ELSIF v_step_id IS NULL THEN
EXECUTE 'SELECT '||v_jobmon_schema||'.add_step('||v_job_id||', ''EXCEPTION before first step logged'')' INTO v_step_id;
END IF;
EXECUTE 'SELECT '||v_jobmon_schema||'.update_step('||v_step_id||', ''CRITICAL'', ''ERROR: '||coalesce(SQLERRM,'unknown')||''')';
EXECUTE 'SELECT '||v_jobmon_schema||'.fail_job('||v_job_id||')';
END IF;
RAISE EXCEPTION '%', SQLERRM;
END
$$;
`)
if err != nil {
log.Printf("%v", err)
}
// check_name_length()
_, err = tx.Exec(`
/*
* Truncate the name of the given object if it is greater than the postgres default max (63 characters).
* Also appends given suffix and schema if given and truncates the name so that the entire suffix will fit.
* Returns original name with schema given if it doesn't require truncation
*/
CREATE FUNCTION partman.check_name_length (p_object_name text, p_object_schema text DEFAULT NULL, p_suffix text DEFAULT NULL, p_table_partition boolean DEFAULT FALSE) RETURNS text
LANGUAGE plpgsql SECURITY DEFINER
AS $$
DECLARE
v_new_length int;
v_new_name text;
BEGIN
IF p_table_partition IS TRUE AND (p_suffix IS NULL OR p_object_schema IS NULL) THEN
RAISE EXCEPTION 'Table partition name requires a schema and suffix value';
END IF;
IF p_table_partition THEN -- 61 characters to account for _p in partition name
IF char_length(p_object_name) + char_length(p_suffix) >= 61 THEN
v_new_length := 61 - char_length(p_suffix);
v_new_name := p_object_schema ||'.'|| substring(p_object_name from 1 for v_new_length) || '_p' || p_suffix;
ELSE
v_new_name := p_object_schema ||'.'||p_object_name||'_p'||p_suffix;
END IF;
ELSE
IF char_length(p_object_name) + char_length(COALESCE(p_suffix, '')) >= 63 THEN
v_new_length := 63 - char_length(COALESCE(p_suffix, ''));
v_new_name := COALESCE(p_object_schema ||'.', '') || substring(p_object_name from 1 for v_new_length) || COALESCE(p_suffix, '');
ELSE
v_new_name := COALESCE(p_object_schema ||'.', '') || p_object_name||COALESCE(p_suffix, '');
END IF;
END IF;
RETURN v_new_name;
END
$$;
`)
if err != nil {
log.Printf("%v", err)
}
// check_parent()
_, err = tx.Exec(`
/*
* Function to monitor for data getting inserted into parent tables managed by extension
*/
CREATE FUNCTION partman.check_parent() RETURNS SETOF partman.check_parent_table
LANGUAGE plpgsql STABLE SECURITY DEFINER
AS $$
DECLARE
v_count bigint = 0;
v_sql text;
v_tables record;
v_trouble partman.check_parent_table%rowtype;
BEGIN
FOR v_tables IN
SELECT DISTINCT parent_table FROM partman.part_config
LOOP
v_sql := 'SELECT count(1) AS n FROM ONLY '||v_tables.parent_table;
EXECUTE v_sql INTO v_count;
IF v_count > 0 THEN
v_trouble.parent_table := v_tables.parent_table;
v_trouble.count := v_count;
RETURN NEXT v_trouble;
END IF;
v_count := 0;
END LOOP;
RETURN;
END
$$;
`)
if err != nil {
log.Printf("%v", err)
}
// check_version()
_, err = tx.Exec(`
/*
* Check PostgreSQL version number. Parameter must be full 3 point version.
* Returns true if current version is greater than or equal to the parameter given.
*/
CREATE FUNCTION partman.check_version(p_check_version text) RETURNS boolean
LANGUAGE plpgsql STABLE
AS $$
DECLARE
v_check_version text[];
v_current_version text[] := string_to_array(current_setting('server_version'), '.');
BEGIN
v_check_version := string_to_array(p_check_version, '.');
IF v_current_version[1]::int > v_check_version[1]::int THEN
RETURN true;
END IF;
IF v_current_version[1]::int = v_check_version[1]::int THEN
IF v_current_version[2]::int > v_check_version[2]::int THEN
RETURN true;
END IF;
IF v_current_version[2]::int = v_check_version[2]::int THEN
IF v_current_version[3]::int >= v_check_version[3]::int THEN
RETURN true;
END IF; -- 0.0.x
END IF; -- 0.x.0
END IF; -- x.0.0
RETURN false;
END
$$;
`)
if err != nil {
log.Printf("%v", err)
}
// create_function_id
_, err = tx.Exec(`
/*
* Create the trigger function for the parent table of an id-based partition set
*/
CREATE FUNCTION partman.create_function_id(p_parent_table text) RETURNS void
LANGUAGE plpgsql SECURITY DEFINER
AS $$
DECLARE
v_control text;
v_count int;
v_current_partition_name text;
v_current_partition_id bigint;
v_datetime_string text;
v_final_partition_id bigint;
v_function_name text;
v_higher_parent text := p_parent_table;
v_id_position int;
v_job_id bigint;
v_jobmon text;
v_jobmon_schema text;
v_last_partition text;
v_max bigint;
v_next_partition_id bigint;
v_next_partition_name text;
v_old_search_path text;
v_parent_schema text;
v_parent_tablename text;
v_part_interval bigint;
v_premake int;
v_prev_partition_id bigint;
v_prev_partition_name text;
v_run_maint boolean;
v_step_id bigint;
v_top_parent text := p_parent_table;
v_trig_func text;
v_type text;
BEGIN
SELECT type
, part_interval::bigint
, control
, premake
, use_run_maintenance
, jobmon
INTO v_type
, v_part_interval
, v_control
, v_premake
, v_run_maint
, v_jobmon
FROM partman.part_config
WHERE parent_table = p_parent_table
AND (type = 'id-static' OR type = 'id-dynamic');
IF NOT FOUND THEN
RAISE EXCEPTION 'ERROR: no config found for %', p_parent_table;
END IF;
SELECT show_partitions INTO v_last_partition FROM partman.show_partitions(p_parent_table, 'DESC') LIMIT 1;
IF v_jobmon THEN
SELECT nspname INTO v_jobmon_schema FROM pg_catalog.pg_namespace n, pg_catalog.pg_extension e WHERE e.extname = 'pg_jobmon' AND e.extnamespace = n.oid;
IF v_jobmon_schema IS NOT NULL THEN
SELECT current_setting('search_path') INTO v_old_search_path;
EXECUTE 'SELECT set_config(''search_path'',''partman,'||v_jobmon_schema||''',''false'')';
END IF;
END IF;
IF v_jobmon_schema IS NOT NULL THEN
v_job_id := add_job('PARTMAN CREATE FUNCTION: '||p_parent_table);
v_step_id := add_step(v_job_id, 'Creating partition function for table '||p_parent_table);
END IF;
SELECT schemaname, tablename INTO v_parent_schema, v_parent_tablename FROM pg_catalog.pg_tables WHERE schemaname ||'.'|| tablename = p_parent_table;
v_function_name := partman.check_name_length(v_parent_tablename, v_parent_schema, '_part_trig_func', FALSE);
IF v_type = 'id-static' THEN
-- Get the highest level top parent if multi-level partitioned in order to get proper max() value below
WHILE v_higher_parent IS NOT NULL LOOP -- initially set in DECLARE
WITH top_oid AS (
SELECT i.inhparent AS top_parent_oid
FROM pg_catalog.pg_inherits i
JOIN pg_catalog.pg_class c ON c.oid = i.inhrelid
JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
WHERE n.nspname||'.'||c.relname = v_higher_parent
) SELECT n.nspname||'.'||c.relname
INTO v_higher_parent
FROM pg_catalog.pg_class c
JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
JOIN top_oid t ON c.oid = t.top_parent_oid
JOIN partman.part_config p ON p.parent_table = n.nspname||'.'||c.relname
WHERE p.type = 'id-static' OR p.type = 'id-dynamic';
IF v_higher_parent IS NOT NULL THEN
-- initially set in DECLARE
v_top_parent := v_higher_parent;
END IF;
END LOOP;
EXECUTE 'SELECT COALESCE(max('||v_control||'), 0) FROM '||v_top_parent INTO v_max;
v_current_partition_id = v_max - (v_max % v_part_interval);
v_next_partition_id := v_current_partition_id + v_part_interval;
v_current_partition_name := partman.check_name_length(v_parent_tablename, v_parent_schema, v_current_partition_id::text, TRUE);
v_trig_func := 'CREATE OR REPLACE FUNCTION '||v_function_name||'() RETURNS trigger LANGUAGE plpgsql AS $t$
DECLARE
v_current_partition_id bigint;
v_last_partition text := '||quote_literal(v_last_partition)||';
v_id_position int;
v_next_partition_id bigint;
v_next_partition_name text;
v_partition_created boolean;
BEGIN
IF TG_OP = ''INSERT'' THEN
IF NEW.'||v_control||' >= '||v_current_partition_id||' AND NEW.'||v_control||' < '||v_next_partition_id|| ' THEN ';
SELECT count(*) INTO v_count FROM pg_catalog.pg_tables WHERE schemaname ||'.'||tablename = v_current_partition_name;
IF v_count > 0 THEN
v_trig_func := v_trig_func || '
INSERT INTO '||v_current_partition_name||' VALUES (NEW.*); ';
ELSE
v_trig_func := v_trig_func || '
-- Child table for current values does not exist in this partition set, so write to parent
RETURN NEW;';
END IF;
FOR i IN 1..v_premake LOOP
v_prev_partition_id := v_current_partition_id - (v_part_interval * i);
v_next_partition_id := v_current_partition_id + (v_part_interval * i);
v_final_partition_id := v_next_partition_id + v_part_interval;
v_prev_partition_name := partman.check_name_length(v_parent_tablename, v_parent_schema, v_prev_partition_id::text, TRUE);
v_next_partition_name := partman.check_name_length(v_parent_tablename, v_parent_schema, v_next_partition_id::text, TRUE);
-- Check that child table exist before making a rule to insert to them.
-- Handles edge case of changing premake immediately after running create_parent().
SELECT count(*) INTO v_count FROM pg_catalog.pg_tables WHERE schemaname ||'.'||tablename = v_prev_partition_name;
IF v_count > 0 THEN
-- Only handle previous partitions if they're starting above zero
IF v_prev_partition_id >= 0 THEN
v_trig_func := v_trig_func ||'
ELSIF NEW.'||v_control||' >= '||v_prev_partition_id||' AND NEW.'||v_control||' < '||v_prev_partition_id + v_part_interval|| ' THEN
INSERT INTO '||v_prev_partition_name||' VALUES (NEW.*); ';
END IF;
END IF;
SELECT count(*) INTO v_count FROM pg_catalog.pg_tables WHERE schemaname ||'.'||tablename = v_next_partition_name;
IF v_count > 0 THEN
v_trig_func := v_trig_func ||'
ELSIF NEW.'||v_control||' >= '||v_next_partition_id||' AND NEW.'||v_control||' < '||v_final_partition_id|| ' THEN
INSERT INTO '||v_next_partition_name||' VALUES (NEW.*);';
END IF;
END LOOP;
v_trig_func := v_trig_func ||'
ELSE
RETURN NEW;
END IF;';
IF v_run_maint IS FALSE THEN
v_trig_func := v_trig_func ||'
v_current_partition_id := NEW.'||v_control||' - (NEW.'||v_control||' % '||v_part_interval||');
IF (NEW.'||v_control||' % '||v_part_interval||') > ('||v_part_interval||' / 2) THEN
v_id_position := (length(v_last_partition) - position(''p_'' in reverse(v_last_partition))) + 2;
v_next_partition_id := (substring(v_last_partition from v_id_position)::bigint) + '||v_part_interval||';
WHILE ((v_next_partition_id - v_current_partition_id) / '||v_part_interval||') <= '||v_premake||' LOOP
v_partition_created := partman.create_partition_id('||quote_literal(p_parent_table)||', ARRAY[v_next_partition_id]);
IF v_partition_created THEN
PERFORM partman.create_function_id('||quote_literal(p_parent_table)||');
PERFORM partman.apply_constraints('||quote_literal(p_parent_table)||');
END IF;
v_next_partition_id := v_next_partition_id + '||v_part_interval||';
END LOOP;
END IF;';
END IF;
v_trig_func := v_trig_func ||'
END IF;
RETURN NULL;
END $t$;';
EXECUTE v_trig_func;
IF v_jobmon_schema IS NOT NULL THEN
PERFORM update_step(v_step_id, 'OK', 'Added function for current id interval: '||v_current_partition_id||' to '||v_final_partition_id-1);
END IF;
ELSIF v_type = 'id-dynamic' THEN
-- The return inside the partition creation check is there to keep really high ID values from creating new partitions.
v_trig_func := 'CREATE OR REPLACE FUNCTION '||v_function_name||'() RETURNS trigger LANGUAGE plpgsql AS $t$
DECLARE
v_count int;
v_current_partition_id bigint;
v_current_partition_name text;
v_id_position int;
v_last_partition text := '||quote_literal(v_last_partition)||';
v_last_partition_id bigint;
v_next_partition_id bigint;
v_next_partition_name text;
v_partition_created boolean;
BEGIN
IF TG_OP = ''INSERT'' THEN
v_current_partition_id := NEW.'||v_control||' - (NEW.'||v_control||' % '||v_part_interval||');
v_current_partition_name := partman.check_name_length('''||v_parent_tablename||''', '''||v_parent_schema||''', v_current_partition_id::text, TRUE);
SELECT count(*) INTO v_count FROM pg_tables WHERE schemaname ||''.''|| tablename = v_current_partition_name;
IF v_count > 0 THEN
EXECUTE ''INSERT INTO ''||v_current_partition_name||'' VALUES($1.*)'' USING NEW;
ELSE
RETURN NEW;
END IF;';
IF v_run_maint IS FALSE THEN
v_trig_func := v_trig_func ||'
IF (NEW.'||v_control||' % '||v_part_interval||') > ('||v_part_interval||' / 2) THEN
v_id_position := (length(v_last_partition) - position(''p_'' in reverse(v_last_partition))) + 2;
v_last_partition_id = substring(v_last_partition from v_id_position)::bigint;
v_next_partition_id := v_last_partition_id + '||v_part_interval||';
IF NEW.'||v_control||' >= v_next_partition_id THEN
RETURN NEW;
END IF;
WHILE ((v_next_partition_id - v_current_partition_id) / '||v_part_interval||') <= '||v_premake||' LOOP
v_partition_created := partman.create_partition_id('||quote_literal(p_parent_table)||', ARRAY[v_next_partition_id]);
IF v_partition_created THEN
PERFORM partman.create_function_id('||quote_literal(p_parent_table)||');
PERFORM partman.apply_constraints('||quote_literal(p_parent_table)||');
END IF;
v_next_partition_id := v_next_partition_id + '||v_part_interval||';
END LOOP;
END IF;';
END IF;
v_trig_func := v_trig_func ||'
END IF;
RETURN NULL;
END $t$;';
EXECUTE v_trig_func;
IF v_jobmon_schema IS NOT NULL THEN
PERFORM update_step(v_step_id, 'OK', 'Added function for dynamic id table: '||p_parent_table);
END IF;
ELSE
RAISE EXCEPTION 'ERROR: Invalid id partitioning type given: %', v_type;
END IF;
IF v_jobmon_schema IS NOT NULL THEN
PERFORM close_job(v_job_id);
EXECUTE 'SELECT set_config(''search_path'','''||v_old_search_path||''',''false'')';
END IF;
EXCEPTION
WHEN OTHERS THEN
IF v_jobmon_schema IS NOT NULL THEN
IF v_job_id IS NULL THEN
EXECUTE 'SELECT '||v_jobmon_schema||'.add_job(''PARTMAN CREATE FUNCTION: '||p_parent_table||''')' INTO v_job_id;
EXECUTE 'SELECT '||v_jobmon_schema||'.add_step('||v_job_id||', ''Partition function maintenance for table '||p_parent_table||' failed'')' INTO v_step_id;
ELSIF v_step_id IS NULL THEN
EXECUTE 'SELECT '||v_jobmon_schema||'.add_step('||v_job_id||', ''EXCEPTION before first step logged'')' INTO v_step_id;
END IF;
EXECUTE 'SELECT '||v_jobmon_schema||'.update_step('||v_step_id||', ''CRITICAL'', ''ERROR: '||coalesce(SQLERRM,'unknown')||''')';
EXECUTE 'SELECT '||v_jobmon_schema||'.fail_job('||v_job_id||')';
END IF;
RAISE EXCEPTION '%', SQLERRM;
END
$$;
`)
if err != nil {
log.Printf("%v", err)
}
// create_function_time()
_, err = tx.Exec(`
/*
* Create the trigger function for the parent table of a time-based partition set
*/
CREATE FUNCTION partman.create_function_time(p_parent_table text) RETURNS void
LANGUAGE plpgsql SECURITY DEFINER
AS $$
DECLARE
v_control text;
v_count int;
v_current_partition_name text;
v_current_partition_timestamp timestamptz;
v_datetime_string text;
v_final_partition_timestamp timestamptz;
v_function_name text;
v_job_id bigint;
v_jobmon boolean;
v_jobmon_schema text;
v_old_search_path text;
v_new_length int;
v_next_partition_name text;
v_next_partition_timestamp timestamptz;
v_parent_schema text;
v_parent_tablename text;
v_part_interval interval;
v_premake int;
v_prev_partition_name text;
v_prev_partition_timestamp timestamptz;
v_step_id bigint;
v_trig_func text;
v_type text;
BEGIN
SELECT type
, part_interval::interval
, control
, premake
, datetime_string
, jobmon
INTO v_type
, v_part_interval
, v_control
, v_premake
, v_datetime_string
, v_jobmon
FROM partman.part_config
WHERE parent_table = p_parent_table
AND (type = 'time-static' OR type = 'time-dynamic' OR type = 'time-custom');
IF NOT FOUND THEN
RAISE EXCEPTION 'ERROR: no config found for %', p_parent_table;
END IF;
IF v_jobmon THEN
SELECT nspname INTO v_jobmon_schema FROM pg_namespace n, pg_extension e WHERE e.extname = 'pg_jobmon' AND e.extnamespace = n.oid;
IF v_jobmon_schema IS NOT NULL THEN
SELECT current_setting('search_path') INTO v_old_search_path;
EXECUTE 'SELECT set_config(''search_path'',''partman,'||v_jobmon_schema||''',''false'')';
END IF;
END IF;
IF v_jobmon_schema IS NOT NULL THEN
v_job_id := add_job('PARTMAN CREATE FUNCTION: '||p_parent_table);
v_step_id := add_step(v_job_id, 'Creating partition function for table '||p_parent_table);
END IF;
SELECT schemaname, tablename INTO v_parent_schema, v_parent_tablename FROM pg_tables WHERE schemaname ||'.'|| tablename = p_parent_table;
v_function_name := partman.check_name_length(v_parent_tablename, v_parent_schema, '_part_trig_func', FALSE);
IF v_type = 'time-static' THEN
CASE
WHEN v_part_interval = '15 mins' THEN
v_current_partition_timestamp := date_trunc('hour', CURRENT_TIMESTAMP) +
'15min'::interval * floor(date_part('minute', CURRENT_TIMESTAMP) / 15.0);
WHEN v_part_interval = '30 mins' THEN
v_current_partition_timestamp := date_trunc('hour', CURRENT_TIMESTAMP) +
'30min'::interval * floor(date_part('minute', CURRENT_TIMESTAMP) / 30.0);
WHEN v_part_interval = '1 hour' THEN
v_current_partition_timestamp := date_trunc('hour', CURRENT_TIMESTAMP);
WHEN v_part_interval = '1 day' THEN
v_current_partition_timestamp := date_trunc('day', CURRENT_TIMESTAMP);
WHEN v_part_interval = '1 week' THEN
v_current_partition_timestamp := date_trunc('week', CURRENT_TIMESTAMP);
WHEN v_part_interval = '1 month' THEN
v_current_partition_timestamp := date_trunc('month', CURRENT_TIMESTAMP);
-- Type time-static plus this interval is the special quarterly interval
WHEN v_part_interval = '3 months' THEN
v_current_partition_timestamp := date_trunc('quarter', CURRENT_TIMESTAMP);
WHEN v_part_interval = '1 year' THEN
v_current_partition_timestamp := date_trunc('year', CURRENT_TIMESTAMP);
END CASE;
v_current_partition_name := partman.check_name_length(v_parent_tablename, v_parent_schema, to_char(v_current_partition_timestamp, v_datetime_string), TRUE);
v_next_partition_timestamp := v_current_partition_timestamp + v_part_interval::interval;
v_trig_func := 'CREATE OR REPLACE FUNCTION '||v_function_name||'() RETURNS trigger LANGUAGE plpgsql AS $t$
BEGIN
IF TG_OP = ''INSERT'' THEN
IF NEW.'||v_control||' >= '||quote_literal(v_current_partition_timestamp)||' AND NEW.'||v_control||' < '||quote_literal(v_next_partition_timestamp)|| ' THEN ';
SELECT count(*) INTO v_count FROM pg_catalog.pg_tables WHERE schemaname ||'.'||tablename = v_current_partition_name;
IF v_count > 0 THEN
v_trig_func := v_trig_func || '
INSERT INTO '||v_current_partition_name||' VALUES (NEW.*); ';
ELSE
v_trig_func := v_trig_func || '
-- Child table for current values does not exist in this partition set, so write to parent
RETURN NEW;';
END IF;
FOR i IN 1..v_premake LOOP
v_prev_partition_timestamp := v_current_partition_timestamp - (v_part_interval::interval * i);
v_next_partition_timestamp := v_current_partition_timestamp + (v_part_interval::interval * i);
v_final_partition_timestamp := v_next_partition_timestamp + (v_part_interval::interval);
v_prev_partition_name := partman.check_name_length(v_parent_tablename, v_parent_schema, to_char(v_prev_partition_timestamp, v_datetime_string), TRUE);
v_next_partition_name := partman.check_name_length(v_parent_tablename, v_parent_schema, to_char(v_next_partition_timestamp, v_datetime_string), TRUE);
-- Check that child table exist before making a rule to insert to them.
-- Handles edge case of changing premake immediately after running create_parent().
SELECT count(*) INTO v_count FROM pg_catalog.pg_tables WHERE schemaname ||'.'||tablename = v_prev_partition_name;
IF v_count > 0 THEN
v_trig_func := v_trig_func ||'
ELSIF NEW.'||v_control||' >= '||quote_literal(v_prev_partition_timestamp)||' AND NEW.'||v_control||' < '||
quote_literal(v_prev_partition_timestamp + v_part_interval::interval)|| ' THEN
INSERT INTO '||v_prev_partition_name||' VALUES (NEW.*);';
END IF;
SELECT count(*) INTO v_count FROM pg_catalog.pg_tables WHERE schemaname ||'.'||tablename = v_next_partition_name;
IF v_count > 0 THEN
v_trig_func := v_trig_func ||'
ELSIF NEW.'||v_control||' >= '||quote_literal(v_next_partition_timestamp)||' AND NEW.'||v_control||' < '||
quote_literal(v_final_partition_timestamp)|| ' THEN
INSERT INTO '||v_next_partition_name||' VALUES (NEW.*);';
END IF;
END LOOP;
v_trig_func := v_trig_func ||'
ELSE
RETURN NEW;
END IF;
END IF;
RETURN NULL;
END $t$;';
EXECUTE v_trig_func;
IF v_jobmon_schema IS NOT NULL THEN
PERFORM update_step(v_step_id, 'OK', 'Added function for current time interval: '||
v_current_partition_timestamp||' to '||(v_final_partition_timestamp-'1sec'::interval));
END IF;
ELSIF v_type = 'time-dynamic' THEN
v_trig_func := 'CREATE OR REPLACE FUNCTION '||v_function_name||'() RETURNS trigger LANGUAGE plpgsql AS $t$
DECLARE
v_count int;
v_partition_name text;
v_partition_timestamp timestamptz;
BEGIN
IF TG_OP = ''INSERT'' THEN
';
CASE
WHEN v_part_interval = '15 mins' THEN
v_trig_func := v_trig_func||'v_partition_timestamp := date_trunc(''hour'', NEW.'||v_control||') +
''15min''::interval * floor(date_part(''minute'', NEW.'||v_control||') / 15.0);';
WHEN v_part_interval = '30 mins' THEN
v_trig_func := v_trig_func||'v_partition_timestamp := date_trunc(''hour'', NEW.'||v_control||') +
''30min''::interval * floor(date_part(''minute'', NEW.'||v_control||') / 30.0);';
WHEN v_part_interval = '1 hour' THEN
v_trig_func := v_trig_func||'v_partition_timestamp := date_trunc(''hour'', NEW.'||v_control||');';
WHEN v_part_interval = '1 day' THEN
v_trig_func := v_trig_func||'v_partition_timestamp := date_trunc(''day'', NEW.'||v_control||');';
WHEN v_part_interval = '1 week' THEN
v_trig_func := v_trig_func||'v_partition_timestamp := date_trunc(''week'', NEW.'||v_control||');';
WHEN v_part_interval = '1 month' THEN
v_trig_func := v_trig_func||'v_partition_timestamp := date_trunc(''month'', NEW.'||v_control||');';
WHEN v_part_interval = '3 months' THEN
v_trig_func := v_trig_func||'v_partition_timestamp := date_trunc(''quarter'', NEW.'||v_control||');';
WHEN v_part_interval = '1 year' THEN
v_trig_func := v_trig_func||'v_partition_timestamp := date_trunc(''year'', NEW.'||v_control||');';
END CASE;
v_trig_func := v_trig_func||'
v_partition_name := partman.check_name_length('''||v_parent_tablename||''', '''||v_parent_schema||''', to_char(v_partition_timestamp, '||quote_literal(v_datetime_string)||'), TRUE);
SELECT count(*) INTO v_count FROM pg_tables WHERE schemaname ||''.''|| tablename = v_partition_name;
IF v_count > 0 THEN
EXECUTE ''INSERT INTO ''||v_partition_name||'' VALUES($1.*)'' USING NEW;
ELSE
RETURN NEW;
END IF;
END IF;
RETURN NULL;
END $t$;';
EXECUTE v_trig_func;
IF v_jobmon_schema IS NOT NULL THEN
PERFORM update_step(v_step_id, 'OK', 'Added function for dynamic time table: '||p_parent_table);