Received: from localhost (unknown [200.46.204.187]) by postgresql.org (Postfix) with ESMTP id 5072D2E3C91 for ; Sat, 5 Jan 2008 13:37:41 -0400 (AST) Received: from postgresql.org ([200.46.204.71]) by localhost (mx1.hub.org [200.46.204.187]) (amavisd-maia, port 10024) with ESMTP id 08067-07 for ; Sat, 5 Jan 2008 13:37:02 -0400 (AST) Received: from momjian.us (momjian.us [70.90.9.53]) by postgresql.org (Postfix) with ESMTP id CE8302E3D89 for ; Sat, 5 Jan 2008 13:37:32 -0400 (AST) Received: (from bruce@localhost) by momjian.us (8.11.6/8.11.6) id m05HbWC08088; Sat, 5 Jan 2008 12:37:32 -0500 (EST) From: Bruce Momjian Message-Id: <200801051737.m05HbWC08088@momjian.us> Subject: Re: Partitioning documentation example In-Reply-To: To: PostgreSQL-documentation Date: Sat, 5 Jan 2008 12:37:32 -0500 (EST) CC: Simon Riggs X-Mailer: ELM [version 2.4ME+ PL124 (25)] MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Content-Type: text/plain; charset="US-ASCII" X-Virus-Scanned: Maia Mailguard 1.0.1 X-Archive-Number: 200801/6 X-Sequence-Number: 4735 bruce wrote: > Simon, I was looking at the new table partitioning documentation that > recommends triggers: > > http://developer.postgresql.org/pgdocs/postgres/ddl-partitioning.html#DDL-PARTITIONING-IMPLEMENTATION > > and came upon this trigger function example: > > CREATE OR REPLACE FUNCTION measurement_insert_trigger() > RETURNS TRIGGER AS $$ > BEGIN > IF ( NEW.logdate >= DATE '2006-02-01' AND NEW.logdate < DATE '2006-03-01' ) THEN > INSERT INTO measurement_y2006m02 VALUES (NEW.*); > ELSIF ( NEW.logdate >= DATE '2006-03-01' AND NEW.logdate < DATE '2006-04-01' ) THEN > INSERT INTO measurement_y2006m03 VALUES (NEW.*); > ... > ELSIF ( NEW.logdate >= DATE '2008-01-01' AND NEW.logdate < DATE '2008-02-01' ) THEN > INSERT INTO measurement_y2008m01 VALUES (NEW.*); > ELSE > RAISE EXCEPTION 'Date out of range. Fix the measurement_insert_trigger() function!'; > END IF; > RETURN NULL; > END; > $$ > LANGUAGE plpgsql; Because my EXECUTE example didn't work I have created a new example using date_trunc(), which I think is less error-prone than the comparisons done in the original example: CREATE OR REPLACE FUNCTION measurement_insert_trigger() RETURNS TRIGGER AS $$ BEGIN IF date_trunc('month', NEW.logdate) = '2006-02-01' THEN INSERT INTO measurement_y2006m02 VALUES (NEW.*); ELSIF date_trunc('month', NEW.logdate) = '2006-03-01' THEN INSERT INTO measurement_y2006m03 VALUES (NEW.*); ... ELSIF date_trunc('month', NEW.logdate) = '2008-01-01' THEN INSERT INTO measurement_y2008m01 VALUES (NEW.*); ELSE RAISE EXCEPTION 'Date out of range. Fix the measurement_insert_trigger() function!'; END IF; RETURN NULL; END; $$ LANGUAGE plpgsql; -- Bruce Momjian http://momjian.us EnterpriseDB http://postgres.enterprisedb.com + If your life is a hard drive, Christ can be your backup. +