The easiest way to enforce this is to add a second foreign key to ticket_type , which refers to the extension table.
The difficulty with this circular dependency is that INSERT in any table will violate the foreign key constraint before you can create another record. You can avoid this by using pending restrictions that will delay the verification of the foreign key until the transaction is completed:
CREATE TABLE ticket_type (id INT PRIMARY KEY); CREATE TABLE myplugin_ticket_type_extension ( id INT PRIMARY KEY, ticket_type_id INT UNIQUE NOT NULL FOREIGN KEY REFERENCES ticket_type (id) DEFERRABLE INITIALLY DEFERRED ); ALTER TABLE ticket_type ADD FOREIGN KEY (id) REFERENCES myplugin_ticket_type_extension (ticket_type_id) DEFERRABLE INITIALLY DEFERRED; BEGIN; INSERT INTO ticket_type VALUES (1); INSERT INTO myplugin_ticket_type_extension VALUES (1,1); COMMIT;
An alternative approach worth considering is to use table inheritance :
CREATE TABLE ticket_type (id INT PRIMARY KEY); CREATE TABLE myplugin_ticket_type_extension (extension_field INT) INHERITS (ticket_type); INSERT INTO myplugin_ticket_type_extension (id, extension_field) VALUES (1,1);
Entries inserted in the extension table will be displayed when ticket_type requested, so your main module should not be affected. You can prevent inserts directly into the ticket_type table by adding a trigger that can either completely block the inserts (by creating an exception) or automatically redirect new entries to the extension table:
CREATE FUNCTION ticket_type_trg() RETURNS TRIGGER AS $$ BEGIN INSERT INTO myplugin_ticket_type_extension (id) VALUES (new.id); RETURN NULL; END $$ LANGUAGE plpgsql; CREATE TRIGGER ticket_type_trg BEFORE INSERT ON ticket_type FOR EACH ROW EXECUTE PROCEDURE ticket_type_trg();
source share