Re: trigger d'historisation

From: "Sihem MOUALHI" <Sihem(dot)MOUALHI(at)cefe(dot)cnrs(dot)fr>
To: "Guillaume Lelarge" <guillaume(at)lelarge(dot)info>
Cc: <pgsql-fr-generale(at)postgresql(dot)org>
Subject: Re: trigger d'historisation
Date: 2011-04-12 15:02:43
Message-ID: 01B930F7330B8F4590FB58789BE3CED58F12BA@ZZML.newcefe.newage.fr
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-fr-generale

En effet, cela fonctionne.

Merci pour votre aide et vos explications.

Sihem MOUALHI

-----Message d'origine-----
De : Guillaume Lelarge [mailto:guillaume(at)lelarge(dot)info]
Envoyé : mardi 12 avril 2011 16:53
À : Sihem MOUALHI
Cc : pgsql-fr-generale(at)postgresql(dot)org
Objet : Re: [pgsql-fr-generale] trigger d'historisation

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

Browse pgsql-fr-generale by date

  From Date Subject
Next Message Alain Benard 2011-04-12 17:32:06 Re: Volumes importants - lenteur.
Previous Message Guillaume Lelarge 2011-04-12 14:53:25 Re: trigger d'historisation