· 7 years ago · Oct 18, 2018, 06:14 PM
1I tried to use declarative partitioning and, to avoid creating partitions by hand, to make them in ON BEFORE STATEMENT trigger. Trigger executes successfully (proved that with RAISE NOTICE), but server crashes.
2
3Error in the log could look like that:
4
5[24329207.147193] postgres[23599]: segfault at 15948 ip 00005652ff2e586e sp 00007fffd9ee5a50 error 4 in postgres[5652ff17d000+6de000]
62018-10-18 14:52:13 MSK [4312]: [17-1] user=,db= LOG: server process (PID 4636) was terminated by signal 11: Segmentation fault
72018-10-18 14:52:13 MSK [4312]: [18-1] user=,db= DETAIL: Failed process was running: INSERT INTO test (value) VALUES (1);
82018-10-18 14:52:13 MSK [4312]: [19-1] user=,db= LOG: terminating any other active server processes
9
10Test case follows:
11
12CREATE TABLE test (id serial NOT NULL, value integer NOT NULL, ctime timestamp NOT NULL DEFAULT now()) PARTITION BY RANGE (ctime);
13
14CREATE OR REPLACE FUNCTION week_table_suffix_from_ts(ts timestamp with time zone) RETURNS text
15 LANGUAGE plpgsql
16 AS $$
17DECLARE
18 table_suffix text := replace(substring((date_trunc('week', ts))::text from 1 for 10),'-','');
19BEGIN
20 RETURN table_suffix;
21END;
22$$;
23
24CREATE OR REPLACE FUNCTION test_trigger_func() RETURNS trigger
25 LANGUAGE plpgsql
26 AS $$
27DECLARE
28 table_prefix text := 'test_';
29 table_suffix text := week_table_suffix_from_ts(now());
30 table_name text := table_prefix || table_suffix;
31 table_exists boolean;
32BEGIN
33 EXECUTE format(
34 'SELECT EXISTS (SELECT 1 FROM pg_tables WHERE schemaname = $1 AND tablename = $2)'
35 ) INTO table_exists USING 'public', table_name;
36
37 IF NOT table_exists THEN
38 EXECUTE format(
39 'CREATE TABLE IF NOT EXISTS %I PARTITION OF test FOR VALUES FROM (%L) TO (%L)'::text,
40 table_name,
41 date_trunc('week', now()),
42 date_trunc('week', now() + interval '1 week')
43 );
44 END IF;
45
46 RETURN NULL;
47END;
48$$;
49
50CREATE TRIGGER test_trigger BEFORE INSERT ON test FOR EACH STATEMENT EXECUTE PROCEDURE test_trigger_func();
51
52INSERT INTO test (value) VALUES (1);