1

1) I have table

CREATE TABLE tor
(
  events_date timestamp without time zone NOT NULL,
  message text
  CONSTRAINT tor_pkey PRIMARY KEY (events_date, message)
)PARTITION BY RANGE (events_date);

2) There is a default partition where the data gets, if there is no partition where you can put it

CREATE TABLE tor_part_default partition OF tor default;

3) There is a trigger on an INSERT to tor_part_default:

CREATE OR REPLACE FUNCTION create_next_part()
    RETURNS trigger
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE NOT LEAKPROOF
AS $BODY$
DECLARE
    partname VARCHAR(11);
    startdate VARCHAR(10);
    enddate VARCHAR(10);
BEGIN
    partname = 'tor_'||to_char(NEW.events_date, 'YYYYMM');
    startdate = to_char(NEW.events_date, 'YYYY-MM-01');
    enddate = to_char(TO_DATE(startdate,'YYYY-MM-DD') + interval '1 month','YYYY-MM-DD');
    RAISE NOTICE '    Start date: %',startdate;
    RAISE NOTICE '      End date: %',enddate;
    IF NOT EXISTS (SELECT 1 FROM   information_schema.tables WHERE  table_name = partname) 
    THEN
        RAISE NOTICE 'Partition created: %',partname;
        EXECUTE 'CREATE TABLE '||partname||' partition OF tor FOR VALUES FROM ('''||startdate||''') TO ('''||enddate||''')';
        EXECUTE 'INSERT INTO '||partname||' VALUES(NEW.*)';
    END IF;
    RETURN NEW;
    END;
    $BODY$;

CREATE TRIGGER tor_create_next_part
    BEFORE INSERT
    ON tor_part_default
    FOR EACH ROW
    EXECUTE PROCEDURE create_next_part();

When I try to insert data, as a result I get an error:

ERROR:  cannot CREATE TABLE .. PARTITION OF "tor" because it is being used by active queries in this session
CONTEXT:  SQL statement "CREATE TABLE tor_201606 partition OF tor FOR VALUES FROM ('2016-06-01') TO ('2016-07-01')"
PL/pgSQL function create_next_part() line 16 at EXECUTE

What am I doing wrong or is there another way to create partitions automatically?

2
  • were you able to solve this? If so, please post the answer here. I am stuck at the same issue.
    – Mir Adnan
    May 17, 2020 at 3:10
  • 1
    @MirAdnan I've posted answer below.
    – Maxiko
    May 18, 2020 at 7:14

1 Answer 1

0

It's not possible to modify table via trigger.

So I have 2 options:

  1. Add partition via cron.
  2. Add partition via code (check default partition).
1
  • I would use a cron job that runs once a year (e.g. in december) and automatically creates the 12 partitions for the next year
    – user1822
    May 18, 2020 at 7:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.