Re: trigger d'historisation

From: Guillaume Lelarge <guillaume(at)lelarge(dot)info>
To: Sihem MOUALHI <Sihem(dot)MOUALHI(at)cefe(dot)cnrs(dot)fr>
Cc: pgsql-fr-generale(at)postgresql(dot)org
Subject: Re: trigger d'historisation
Date: 2011-04-12 14:53:25
Message-ID: 4DA46765.8010905@lelarge.info
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-fr-generale

Le 12/04/2011 16:37, Sihem MOUALHI a écrit :
> Voici le code du trigger que j'utilise:
>
> CREATE OR REPLACE FUNCTION histo_table() RETURNS TRIGGER AS $histo_table$
>
> BEGIN
>
> IF (TG_OP = 'DELETE') THEN
>
> INSERT INTO history_table (date, attribut2, attribut3,...)
> SELECT now(), OLD.attribut2, OLD.attribut3,..
> FROM matable;
>
> ELSIF (TG_OP = 'UPDATE') THEN
>
> INSERT INTO history_table (date, attribut2, attribut3,...)
> SELECT now(), OLD.attribut2, OLD.attribut3,..
> FROM matable;
> END IF;
>
> RETURN NULL;
> END;
>

Donc c'est bien une fonction trigger buggée, même si je n'ai pas compris
immédiatement pourquoi :)

Donc, en gros, vous exécutez ceci :

INSERT INTO history_table (date, attribut2, attribut3,...)
SELECT now(), OLD.attribut2, OLD.attribut3,..
FROM matable;

Si vous avez deux lignes dans la table, votre trigger AFTER s'exécute
alors que la ligne est supprimée. Cependant, vous aviez deux lignes, le
SELECT ramène une seule ligne, donc vous avez votre insertion.

Si maintenant vous exécutez un DELETE sur votre table qui ne contient
plus qu'une ligne, le SELECT ramène 0 lignes, d'où pas d'insertion.

Bref, pour corriger votre erreur, supprimer le SELECT. Vous obtiendrez
ceci :

INSERT INTO history_table (date, attribut2, attribut3,...)
VALUES (now(), OLD.attribut2, OLD.attribut3, ...);

--
Guillaume
http://www.postgresql.fr
http://dalibo.com

In response to

Responses

Browse pgsql-fr-generale by date

  From Date Subject
Next Message Sihem MOUALHI 2011-04-12 15:02:43 Re: trigger d'historisation
Previous Message Daniel Verite 2011-04-12 14:48:51 Re: trigger d'historisation