Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save itailulu/c2818632fa05ec792df03ae985d2d6e8 to your computer and use it in GitHub Desktop.
Save itailulu/c2818632fa05ec792df03ae985d2d6e8 to your computer and use it in GitHub Desktop.
Create monthly partitions for a partitioned table in Postgres
/**
Running 'SELECT create_monthly_partitions_for_partitioned_table( 'party_test', '2021-11-15', '2022-01-15' );'
Will result in executing the following statements:
`CREATE TABLE party_test_y2021_m11 PARTITION OF party_test FOR VALUES FROM ('2021-11-01 00:00:00+00') TO ('2021-12-01 00:00:00+00');`
`CREATE TABLE party_test_y2021_m12 PARTITION OF party_test FOR VALUES FROM ('2021-12-01 00:00:00+00') TO ('2022-01-01 00:00:00+00');`
`CREATE TABLE party_test_y2022_m01 PARTITION OF party_test FOR VALUES FROM ('2022-01-01 00:00:00+00') TO ('2022-02-01 00:00:00+00');`
*/
CREATE OR REPLACE FUNCTION create_monthly_partitions_for_partitioned_table(base_table TEXT, start_month DATE, end_month DATE) RETURNS VOID AS
$$
DECLARE
create_query TEXT;
BEGIN
FOR create_query IN SELECT FORMAT('
CREATE TABLE IF NOT EXISTS %1$s_%2$s PARTITION OF %1$s
FOR VALUES FROM (''%3$s'') TO (''%4$s'');
', base_table, TO_CHAR(d, '"y"yyyy_"m"MM'), d::DATE, (d + INTERVAL '1 month')::DATE)
FROM GENERATE_SERIES(CAST(DATE_TRUNC('month', start_month) AS DATE),
CAST(DATE_TRUNC('month', end_month) AS DATE), '1 month') AS d
LOOP
EXECUTE create_query;
END LOOP;
END;
$$ LANGUAGE plpgsql
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment