(注意:更新为下面采用的答案。)
对于 PostgreSQL 8.1(或更高版本)分区表,如果意味着更改定义分区隔离的受约束字段,如何定义UPDATE
触发器和过程以将记录从一个分区“移动”到另一个分区?UPDATE
例如,我有一个表记录分区为活动和非活动记录,如下所示:
create table RECORDS (RECORD varchar(64) not null, ACTIVE boolean default true);
create table ACTIVE_RECORDS ( check (ACTIVE) ) inherits RECORDS;
create table INACTIVE_RECORDS ( check (not ACTIVE) ) inherits RECORDS;
触发器和函数运行良好:新的INSERT
活动记录放在一个表中,新的非活动记录放在另一个表中。我希望UPDATE
ACTIVE 字段将记录从一个后代表“移动”到另一个,但遇到一个错误,表明这可能是不可能的。
触发规范和错误信息:
pg=> CREATE OR REPLACE FUNCTION record_update()
RETURNS TRIGGER AS $$
BEGIN
IF (NEW.active = OLD.active) THEN
RETURN NEW;
ELSIF (NEW.active) THEN
INSERT INTO active_records VALUES (NEW.*);
DELETE FROM inactive_records WHERE record = NEW.record;
ELSE
INSERT INTO inactive_records VALUES (NEW.*);
DELETE FROM active_records WHERE record = NEW.record;
END IF;
RETURN NULL;
END;
$$
LANGUAGE plpgsql;
pg=> CREATE TRIGGER record_update_trigger
BEFORE UPDATE ON records
FOR EACH ROW EXECUTE PROCEDURE record_update();
pg=> select * from RECORDS;
record | active
--------+--------
foo | t -- 'foo' record actually in table ACTIVE_RECORDS
bar | f -- 'bar' record actually in table INACTIVE_RECORDS
(2 rows)
pg=> update RECORDS set ACTIVE = false where RECORD = 'foo';
ERROR: new row for relation "active_records" violates check constraint "active_records_active_check"
使用触发器过程(返回 NULL 等)向我建议在调用触发器之前检查约束并引发错误,这意味着我当前的方法将不起作用。这可以工作吗?
更新/回答
下面是UPDATE
我最终使用的触发程序,分配给每个分区的程序相同。完全归功于 Bell,他的回答给了我在分区上触发的关键见解:
CREATE OR REPLACE FUNCTION record_update()
RETURNS TRIGGER AS $$
BEGIN
IF ( (TG_TABLE_NAME = 'active_records' AND NOT NEW.active)
OR
(TG_TABLE_NAME = 'inactive_records' AND NEW.active) ) THEN
DELETE FROM records WHERE record = NEW.record;
INSERT INTO records VALUES (NEW.*);
RETURN NULL;
END IF;
RETURN NEW;
END;
$$
LANGUAGE plpgsql;