title: Trigger caused by an update statement inside another trigger
body: <p>Suppose I have the following tables:</p>
  
  <pre><code>CREATE TABLE foo (
    id_foo int NOT NULL,
    import int NOT NULL,
    CONSTRAINT foo_pk PRIMARY KEY(id_foo)
  );
  
  CREATE TABLE bar (
    id_bar int NOT NULL,
    id_foo int NOT NULL,
    import int NOT NULL,
    CONSTRAINT bar_pk PRIMARY KEY(id_bar)
  );
  
  ALTER TABLE bar ADD CONSTRAINT fk_bar FOREIGN KEY(id_foo) REFERENCES foo(id_foo);
  </code></pre>
  
  <p>So, the import column of the foo table must equal the sum of the import column in bar table.</p>
  
  <pre><code>CREATE OR REPLACE FUNCTION foo_restriction() RETURNS TRIGGER AS
  $$
    BEGIN
      IF (NEW.import != (SELECT COALESCE(SUM(import),0) FROM bar WHERE id_foo = NEW.id_foo)) THEN
        RAISE EXCEPTION 'import column in foo must be equal in bar table.';
      END IF;
  
      RETURN NEW;
    END;
  $$
  LANGUAGE plpgsql;
  </code></pre>
  
  <p>But I want to automatically sum the new import value in bar to the foo reference.</p>
  
  <pre><code>CREATE OR REPLACE FUNCTION bar_insert() RETURNS TRIGGER AS
  $$
    BEGIN
      UPDATE foo SET import = import + NEW.import WHERE id_foo = NEW.id_foo;
      RETURN NEW;
    END;
  $$
  LANGUAGE plpgsql;
  
  
  CREATE TRIGGER TR_fooRestriction AFTER INSERT OR UPDATE ON foo FOR EACH ROW EXECUTE PROCEDURE foo_restriction();
  CREATE TRIGGER TR_barInsert AFTER INSERT ON bar FOR EACH ROW EXECUTE PROCEDURE bar_insert();
  </code></pre>
  
  <p>Then the following statement should not work:</p>
  
  <pre><code>INSERT INTO foo(id_foo, import) VALUES(1,25); --FAIL. Works ok.
  </code></pre>
  
  <p>The following instruction insert a correct tuple for foo, with import = 0.</p>
  
  <pre><code>INSERT INTO foo(id_foo, import) VALUES(2,0); --OK.
  </code></pre>
  
  <p>But, when I'm trying to add new values in the bat table, the database show me 'import column in foo must be equal in bar table.':</p>
  
  <pre><code>INSERT INTO bar(id_bar, id_foo, import) VALUES
  (1,2,100),(2,2,160),(3,2,40);
  </code></pre>
  
  <p>Whats happening here?, both triggers are executed after each new row, so the restriction in foo table should not be activated in the last statement.</p>
  
  <p>How can I do to fix it?</p>
  
  <p>Thanks!</p>