实现说明
这个文件依次执行 INSERT / UPDATE / CREATE 语句,涉及 team_members、of。
team_members 是文件自己造的会话级临时表——库里不会有残留,会话终结即被清理。
从子句角度看,用到了:WHERE 决定这条语句会作用到哪些行;必填列上的 NOT NULL 限定;强制行身份的 PRIMARY KEY;补齐缺省列的 DEFAULT 值。
常见问题
这里用到哪些关系?
team_members、of——直接引用,无需连接。
核心语句
CREATE CONSTRAINT TRIGGER lead_cap_on_promote
AFTER INSERT OR UPDATE OF is_lead ON team_members
DEFERRABLE INITIALLY DEFERRED
FOR EACH ROW EXECUTE FUNCTION enforce_lead_cap();
UPDATE team_members SET is_lead = true WHERE emp_id = 15;
UPDATE team_members SET is_lead = false WHERE emp_id = 7;
代码示例
-- some rules only hold for the whole set: promote a member first, remove a
-- lead afterwards -- a per-row CHECK cannot express that. A constraint
-- trigger defers validation to COMMIT and lets the transaction sit
-- temporarily over cap in between.
CREATE TEMP TABLE team_members (
emp_id integer PRIMARY KEY,
team text NOT NULL,
is_lead boolean NOT NULL DEFAULT false
);
-- seed rows: team core already has two leads (emp 7 and emp 12); emp 15 is a regular member
INSERT INTO team_members VALUES
(7, 'core', true),
(12, 'core', true),
(15, 'core', false);
CREATE OR REPLACE FUNCTION enforce_lead_cap() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
-- at commit time scan the team's current state, not just the row that fired
IF (SELECT count(*) FROM team_members WHERE team = NEW.team AND is_lead) > 2 THEN
RAISE EXCEPTION 'team % already has two leads', NEW.team;
END IF;
RETURN NULL;
END;
$$;
-- a constraint trigger must be an AFTER row-level trigger; DEFERRABLE INITIALLY
-- DEFERRED moves the check to commit time
CREATE CONSTRAINT TRIGGER lead_cap_on_promote
AFTER INSERT OR UPDATE OF is_lead ON team_members
DEFERRABLE INITIALLY DEFERRED
FOR EACH ROW EXECUTE FUNCTION enforce_lead_cap();
BEGIN;
-- three temporary leads in between (7, 12, 15) raise nothing: validation happens at COMMIT
UPDATE team_members SET is_lead = true WHERE emp_id = 15;
UPDATE team_members SET is_lead = false WHERE emp_id = 7;
COMMIT; -- passes: exactly two leads (12 and 15) remain at commit time
-- a transaction that still exceeds the cap at commit is rejected and rolled
-- back as a whole: no intermediate state ever leaks
BEGIN;
UPDATE team_members SET is_lead = true WHERE emp_id = 7;
COMMIT; -- ERROR: team core already has two leads