標籤:before sql now() pac its gui blank declare 批量
與Oracle不同。PostgreSQL須要手動控制分區規則引發器。
步驟一:建立分區
CREATE TABLE table_partition_1( CHECK partition_column criteria) INHENRITS (table)
步驟二:為分區表建立PK跟index,這裡使用btree
ALTER TABLE ONLY table_partition_1 ADD CONSTRAINT table_partition_1_pkey PRIMARY KEY (key_column);
CREATE INDEX index_table_partition_1 ON table_partition_1 USING btree(column);
步驟三:手動建立觸發器
CREATE OR REPLACE FUNCTION before_insert_table() RETURNS trigger AS$BODY$ DECLARE BEGINif criteria thenEXECUTE 'insert into appropriate table ...' SELECT ($1).* ' USING NEW;end if;return null;END;$BODY$ LANGUAGE plpgsql VOLATILE COST 100;ALTER FUNCTION before_insert_table() OWNER TO db;
rule在大量操作時更合適,可是對於單獨操作會佔用較大的開銷。
CREATE RULE table_partition_1 _insert AS(criteria ...)DO INSTEAD INSERT INTO table_partition_1 VALUES (NEW.*)
步驟四:觸發器方式hibernate向分區插入資料時。獲得的result count為0,會導致推斷失敗而復原。
解決方案是使用rule,或者聲明分區插入時不進行result檢查。
@SQLInsert(sql = "INSERT INTO "+ "table(column,...)"+ " VALUES(?,...)", check = ResultCheckStyle.NONE)
在Java項目中。考慮到分區建立會採用job方式自己主動建立,能夠通過function完畢建立。
CREATE OR REPLACE FUNCTION "public"."function"() RETURNS void AS $BODY$ DECLARE _tablename text ; quarter integer;record1 record; BEGINselect function(now()) as quarter into record1; quarter := record1.quarter;_tablename := 'partition_name';PERFORM 1FROM pg_catalog.pg_class cWHERE c.relname = _tablename;IF FOUND <> TRUE THENEXECUTE 'CREATE TABLE ' || _tablename || ' ( CHECK ( criteria) ) INHERITS (table)';EXECUTE 'ALTER TABLE ' || _tablename || ' OWNER TO db ';EXECUTE ' alter table ' || _tablename || ' add CONSTRAINT ' || _tablename||'_pkey PRIMARY key (column) ' ;EXECUTE ' CREATE INDEX ' || _tablename|| '_indexON '|| _tablename ||'USING btree(column)'; END IF;END$BODY$ LANGUAGE 'plpgsql' VOLATILE COST 100;ALTER FUNCTION "public"."function"() OWNER TO "db";
參考資料:entity-hibspec-customsql.html
postgresql-table-partitioning-hibernate.html
PostgreSql Partition + Hibernate Insert