How to create automatic partitions on a non-time based column in Postgres?
-
11-03-2021 - |
سؤال
I want to create a partition on a column which is of type serial
. A hash based partition seems appropriate here. But from what I understand I will need to create all the partitions myself (based on remainder). Is there a way to create all the partitions (say 10 partitions) using some automated extension like pg-partman?
المحلول
There is nothing built into Postgres to do "automatic partition creation", so you either need to write a little script that automates that process or use a tool like pg_partman if it supports that.
In psql
you could use a query like this to generate the create table
statements and then run it using \g
:
select format('create table %I partition of my_table for values with (modulus 10, remainder %s);', 'my_table_p'||to_char(g.i, 'FM00'), g.i)
from generate_series(0,9) as g(i)
\g
Otherwise just use a do
block:
do
$$
declare
l_sql text;
begin
for i in 0..9 loop
l_sql := format('create table %I partition of my_table for values with (modulus 10, remainder %s)', 'my_table_p'||to_char(i, 'FM00'), i);
execute l_sql;
end loop;
end;
$$
;
Not tested!
Of course you can put the PL/pgSQL loop into a function or procedure and call it with the number of partitions you want.