我想做每日分区。我知道oracle就是这样的。
CREATE TABLE "PUBLIC"."TEST"
(
"ID" NUMBER(38,0) NOT NULL ENABLE,
"SOME_FIELD" VARCHAR2(20 BYTE) NOT NULL ENABLE,
"ANOTHER_FIELD" VARCHAR2(36 BYTE) NOT NULL ENABLE,
TABLESPACE "PUBLIC"."TEST_DATA"
PARTITION BY RANGE ("TEST_DATE") INTERVAL (NUMTODSINTERVAL(1,'DAY'))
(PARTITION "TEST_P1"
VALUES LESS THAN (TIMESTAMP' 2019-01-01 00:00:00') TABLESPACE "TEST_DATA" );
那么PostgreSQL呢?
新编辑:示例脚本:
将在一个表中保存前15天数据的脚本在另一个分区中说“p1”和剩余天数据。
1-创建自动分区取决于insert命令的日期范围
2-在脚本中我还提到了我们如何在所需列上添加索引。
3-日期范围从1到14的数据将添加到分区“p1”中,剩余的数据将添加到分区“p2”中。
示例脚本:
CREATE TABLE measurement (
city_id int not null,
logdate date not null,
peaktemp int,
unitsales int
);
CREATE OR REPLACE FUNCTION new_partition_creator() RETURNS trigger AS
$BODY$
DECLARE
partition_date TEXT;
partition TEXT;
partition_day int;
startdate date;
enddate date;
BEGIN
partition_day := to_char(NEW.logdate,'DD');
partition_date := to_char(NEW.logdate,'YYYY_MM');
IF partition_day < 15 THEN
partition := TG_RELNAME || '_' || partition_date || '_p1';
startdate := to_char(NEW.logdate,'YYYY-MM-01');
enddate := date_trunc('MONTH', NEW.logdate) + INTERVAL '1 MONTH - 1 day';
ELSE
partition := TG_RELNAME || '_' || partition_date || '_p2';
startdate := to_char(NEW.logdate,'YYYY-MM-15');
enddate := date_trunc('MONTH', NEW.logdate) + INTERVAL '1 MONTH - 1 day';
END IF;
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 ( logdate >= DATE ''' || startdate || ''' AND logdate <= DATE ''' || enddate || ''' )) INHERITS (' || TG_RELNAME || ');';
EXECUTE 'CREATE INDEX ' || partition || '_logdate ON ' || partition || '(logdate)';
EXECUTE 'ALTER TABLE ' || partition || ' add primary key(city_id);';
END IF;
EXECUTE 'INSERT INTO ' || partition || ' SELECT(' || TG_RELNAME || ' ' || quote_literal(NEW) || ').* RETURNING city_id;';
RETURN NULL;
END;
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;
CREATE TRIGGER testing_partition_insert_trigger BEFORE INSERT ON measurement FOR EACH ROW EXECUTE PROCEDURE new_partition_creator();
postgres=# insert into measurement values(1,'2017-10-11',10,10);
NOTICE: A partition has been created measurement_2017_10_p1
INSERT 0 0
Postgres确实支持对值进行分区。但是,它不会是自动的,因为您需要在创建基表后手动创建分区,从Postgres 10开始,它们不会自动生成。
请参阅以下链接:https://www.postgresql.org/docs/10/ddl-partitioning.html
看看这个例子是否有意义:
CREATE TABLE PartTest
(
idx INTEGER,
partMe Date
) PARTITION BY LIST (partMe);
CREATE TABLE PartTest_2019_04_11 PARTITION OF PartTest
FOR VALUES IN ('2019-04-11');
您可以使用扩展名pg_partman来创建自动分区。 https://github.com/pgpartman/pg_partman
或者您甚至可以使用scheduler pg_agent,您将在每天18:00:00执行一个过程来创建下一天的分区。