postgres在TRIGGER中INSERT之前更新NEW变量

时间:2017-03-09 08:23:04

标签: postgresql triggers

我有两张表accountsprojects

create table accounts (
  id          bigserial primary key,
  slug        text unique
);


create table projects (
  id          bigserial primary key,
  account_id  bigint not null references accounts (id),
  name        text
);

我希望能够通过仅指定projects(而非account.slug)将新行插入account.id。我想要实现的是:

INSERT into projects (account_slug, name) values ('account_slug', 'project_name');

我考虑使用触发器(不幸的是它不起作用):

create or replace function trigger_projects_insert() returns trigger as $$
begin
  if TG_OP = 'INSERT' AND NEW.account_slug then

    select id as account_id
      from accounts as account
      where account.slug = NEW.account_slug;

    NEW.account_id = account_id;

    -- we should also remove NEW.account_slug but don't know how

  end if;
  return NEW;
end;
$$ LANGUAGE plpgsql;

create trigger trigger_projects_insert before insert on projects
  for each row execute procedure trigger_projects_insert();

达到我想要做的最好方法是什么?

触发器是个好主意吗? 还有其他解决方案吗?

1 个答案:

答案 0 :(得分:1)

WITH newacc AS (
   INSERT INTO accounts (slug)
      VALUES ('account_slug')
      RETURNING id
)
INSERT INTO projects (account_id, name)
   SELECT id, 'project_name'
      FROM newacct;

如果您可以使用的SQL受限,另一个想法可能是在两个表上定义一个视图,并在视图上创建一个INSTEAD OF INSERT触发器,该触发器在底层执行两个INSERT表。然后像你问题中那样的INSERT语句就可以了。