为什么引用数据在引用时仍然不可用?

时间:2017-01-27 10:19:49

标签: postgresql triggers database-trigger

我有下一个关系(我只留下相关的字段):

CREATE TABLE "operations" (
  "id" serial NOT NULL,
  "opdate" timestamp DEFAULT current_timestamp NOT NULL,
);

CREATE TABLE "prows" (
  "id" serial NOT NULL,
  "operation_id" integer NOT NULL,
);

ALTER TABLE "prows" ADD CONSTRAINT "prows_fk_operation_id" FOREIGN KEY ("operation_id")
  REFERENCES "operations" ("id") ON DELETE CASCADE ON UPDATE RESTRICT;

CREATE TRIGGER "prow_bd_changesaldo" before delete
  ON "prows" FOR EACH row EXECUTE PROCEDURE make_prow()
;

CREATE FUNCTION "make_prow" ()
 RETURNS TRIGGER
 LANGUAGE plpgsql
 AS $$
    DECLARE _count INT;
     BEGIN

    SELECT count(*) /* OP.OpDate */
      FROM Operations OP
      WHERE OP.ID = OLD.Operation_ID
      INTO _count;

    RAISE NOTICE 'COUNT: %', _count;

    ...

    IF TG_OP = 'DELETE' THEN RETURN OLD; ELSE RETURN NULL; END IF;/**/
    END;/**/
$$

我知道count为零:

delete from operations ;
NOTICE:  COUNT: 0
CONTEXT:  PL/pgSQL function make_prow() line 1 at RAISE
SQL statement "DELETE FROM ONLY "public"."prows" WHERE $1 OPERATOR(pg_catalog.=) "operation_id""
...

当引用的行消失时,相关的行仍然存在。这对我来说似乎很不一致,打破了诚信。

有没有办法从Operations.OpDate触发器中获取make_prow值?

1 个答案:

答案 0 :(得分:1)

DELETE仅在prows中的行被删除后才operations级联,这并不奇怪。

要解决此问题,您可以将ON DELETE CASCADE更改为ON DELETE NO ACTION并在BEFORE上定义operations触发器,删除prows 之前删除operations中的行。这样,prows中的行将在operations中的行消失之前被调用。