Received: from localhost (unknown [200.46.204.182]) by postgresql.org (Postfix) with ESMTP id 8A01C2E07B2 for ; Thu, 27 Dec 2007 13:52:38 -0400 (AST) Received: from postgresql.org ([200.46.204.71]) by localhost (mx1.hub.org [200.46.204.182]) (amavisd-maia, port 10024) with ESMTP id 15758-05 for ; Thu, 27 Dec 2007 13:52:34 -0400 (AST) Received: from smtp136.iad.emailsrvr.com (smtp136.iad.emailsrvr.com [207.97.245.136]) by postgresql.org (Postfix) with ESMTP id 215062E034D for ; Thu, 27 Dec 2007 13:52:35 -0400 (AST) Received: from relay3.r3.iad.emailsrvr.com (localhost [127.0.0.1]) by relay3.r3.iad.emailsrvr.com (SMTP Server) with ESMTP id 5C9B844C2E4; Thu, 27 Dec 2007 12:52:29 -0500 (EST) Received: by relay3.r3.iad.emailsrvr.com (Authenticated sender: erik-AT-myemma.com) with ESMTP id 32E0844C2F0; Thu, 27 Dec 2007 12:52:29 -0500 (EST) In-Reply-To: <781842.52422.qm@web31813.mail.mud.yahoo.com> References: <781842.52422.qm@web31813.mail.mud.yahoo.com> Mime-Version: 1.0 (Apple Message framework v752.3) Content-Type: text/plain; charset=ISO-8859-1; delsp=yes; format=flowed Message-Id: <5DD016CF-7FDE-489F-B15A-58B6935B4FBD@myemma.com> Cc: SQL Postgresql List Content-Transfer-Encoding: quoted-printable From: Erik Jones Subject: Re: Advice for generalizing trigger functions Date: Thu, 27 Dec 2007 11:51:59 -0600 To: Richard Broersma Jr X-Mailer: Apple Mail (2.752.3) X-Virus-Scanned: Maia Mailguard 1.0.1 X-Archive-Number: 200712/144 X-Sequence-Number: 29836 On Dec 25, 2007, at 6:20 PM, Richard Broersma Jr wrote: > I've created quite a few functions that log modifications to =20 > various history tables. (the history table has the same name as the =20= > base table but is prefixed by the 'History.' schema.) The only =20 > difference between functions I can find is the table name. > > Is there any way to generalize these myriad of functions into one? > > > Below is a sample of a typical logging trigger function. > > Regards, > Richard Broersma Jr. > > > CREATE OR REPLACE FUNCTION "project"."log_managers_ops"() > RETURNS trigger AS > $BODY$ > BEGIN > > > IF TG_OP IN ( 'UPDATE', 'DELETE' ) THEN > > UPDATE History.Managers AS M > SET endts =3D now() > WHERE M.manager_id =3D OLD.manager_id > AND now() BETWEEN M.startts AND M.endts; > > end IF; > > > IF TG_OP IN ( 'UPDATE', 'INSERT' ) THEN > > INSERT INTO History.Managers > VALUES ( now()::timestamptz, 'INFINITY'::timestamptz, =20 > NEW.*); > > RETURN NEW; > > END IF; > > RETURN OLD; > > END; > $BODY$ > LANGUAGE 'plpgsql' VOLATILE SECURITY DEFINER; TG_TABLE_NAME will have the name of the table the trigger was fired =20 on. With that and using EXECUTE for your INSERT statements, you'll =20 probably be set. Erik Jones Software Developer | Emma=AE erik@myemma.com 800.595.4401 or 615.292.5888 615.292.0777 (fax) Emma helps organizations everywhere communicate & market in style. Visit us online at http://www.myemma.com