You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
CREATETABLEIF NOT EXISTS order
(
id varchar(36) NOT NULL,
created_at timestamp(3) with time zoneNOT NULL,
updated_at timestamp(3) with time zoneNOT NULL,
delivered_at timestamp(3) with time zoneNOT NULL,
status intprimary key (id, created_at)
)
PARTITION BY RANGE (created_at);
Function to add monthly partition
CREATE OR REPLACEFUNCTIONcreate_monthly_partition(
yyyymm_start int,
yyyymm_end int,
table_name text,
hash_key text
)
RETURNS text
LANGUAGE 'plpgsql'AS $$
DECLARE
partition_name varchar(50);
approximate_row_count bigint;
modulus int;
sqltext text;
BEGIN
IF NOT EXISTS
(SELECT1FROMinformation_schema.tablesWHERE table_name = table_name)
THEN
RETURN '';
END IF;
-- get partition name to be created
partition_name = table_name ||'_'|| yyyymm_start;
-- check if it has already been created
IF NOT EXISTS
(SELECT1FROMinformation_schema.tablesWHERE table_name = partition_name)
THEN
-- modulus can be changed with the increase of data
modulus =2;
-- partitioned by month
sqltext ='CREATE TABLE '|| table_name ||'_'|| yyyymm_start ||' PARTITION OF '|| table_name ||' FOR VALUES FROM ('||''''|| yyyymm_start ||'01'||''''||') TO ('||''''|| yyyymm_end ||'01'||''''||') PARTITION BY HASH ('|| hash_key ||');';
EXECUTE sqltext;
-- partitioned by modulus
FOR counter IN0..(modulus -1) BY 1 LOOP
sqltext ='CREATE TABLE '|| table_name ||'_'|| yyyymm_start ||'_'|| counter ||' PARTITION OF '|| table_name ||'_'|| yyyymm_start ||' FOR VALUES WITH (MODULUS '|| modulus ||', REMAINDER '|| counter ||');';
EXECUTE sqltext;
END LOOP;
END IF;
RETURN '';
END
$$;