Skip to content

Instantly share code, notes, and snippets.

@l1x
Last active April 23, 2024 11:36
Show Gist options
  • Select an option

  • Save l1x/da842434fe072cf466a1 to your computer and use it in GitHub Desktop.

Select an option

Save l1x/da842434fe072cf466a1 to your computer and use it in GitHub Desktop.
Creating PostgreSQL table partitions automatically based on the date field (type date as well) -- each day is a single partition
CREATE TABLE testing_partition(patent_id BIGINT, date DATE) WITH ( OIDS=FALSE);
CREATE OR REPLACE FUNCTION create_partition_and_insert() RETURNS trigger AS
$BODY$
DECLARE
partition_date TEXT;
partition TEXT;
BEGIN
partition_date := to_char(NEW.date,'YYYY_MM_DD');
partition := TG_TABLE_NAME || '_' || partition_date;
IF NOT EXISTS(SELECT relname FROM pg_class WHERE relname=partition) THEN
RAISE NOTICE 'A partition has been created %',partition;
EXECUTE 'CREATE TABLE ' || partition || ' (check (date = ''' || NEW.date || ''')) INHERITS (' || TG_TABLE_NAME || ');';
END IF;
EXECUTE 'INSERT INTO ' || partition || ' SELECT(' || TG_RELNAME || ' ' || quote_literal(NEW) || ').*;';
RETURN NULL;
END;
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;
CREATE TRIGGER testing_partition_insert_trigger
BEFORE INSERT ON testing_partition
FOR EACH ROW EXECUTE PROCEDURE create_partition_and_insert();
@mollusk
Copy link

mollusk commented Nov 30, 2022

This is very helpful. Looks like TG_RELNAME is deprecated, and TG_TABLE_NAME should be used instead.

@l1x
Copy link
Author

l1x commented Dec 2, 2022

This is very helpful. Looks like TG_RELNAME is deprecated, and TG_TABLE_NAME should be used instead.

Thanks! I am going to update the script.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment