I currently have a parent table:
CREATE TABLE members (
member_id SERIAL NOT NULL, UNIQUE, PRIMARY KEY
first_name varchar(20)
last_name varchar(20)
address address (composite type)
contact_numbers varchar(11)[3]
date_joined date
type varchar(5)
);
and two related tables:
CREATE TABLE basic_member (
activities varchar[3])
INHERITS (members)
);
CREATE TABLE full_member (
activities varchar[])
INHERITS (members)
);
If the type is full the details are entered to the full_member table or if type is basic into the basic_member table. What I want is that if I run an update and change the type to basic or full the tuple goes into the corresponding table.
I was wondering if I could do this with a rule like:
CREATE RULE tuple_swap_full
AS ON UPDATE TO full_member
WHERE new.type = 'basic'
INSERT INTO basic_member VALUES (old.member_id, old.first_name, old.last_name,
old.address, old.contact_numbers, old.date_joined, new.type, old.activities);
… then delete the record from the full_member
Just wondering if my rule is anywhere near or if there is a better way.
You don’t need
A
PRIMARY KEYimpliesUNIQUE NOT NULLautomatically:I wouldn’t use hard coded max length of
varchar(20). Just usetextand add a check constraint if you really must enforce a maximum length. Easier to change around.Syntax for
INHERITSis mangled. The key word goes outside the parens around columns.Table names are inconsistent (
members<->member). I use the singular form everywhere in my test case.Finally, I would not use a RULE for the task. A trigger
AFTER UPDATEseems preferable.Consider the following
Test case:
Tables:
Trigger function:
Data-modifying CTEs (
WITH x AS ( DELETE ..) are the best tool for the purpose. Requires PostgreSQL 9.1 or later.For older versions, first
INSERTthenDELETE.Trigger:
Note that it is an
AFTERtrigger and has aWHENcondition.WHENcondition requires PostgreSQL 9.0 or later. For earlier versions, you can just leave it away, the CASE statement in the trigger itself takes care of it.Test: