2

I am trying to simplify my code via inheritance. Here is what I have right now

DROP SCHEMA PUBLIC CASCADE;
CREATE SCHEMA PUBLIC;

CREATE TABLE student(
   id SERIAL PRIMARY KEY,
   age INT
);

CREATE TABLE engineer(
   id SERIAL PRIMARY KEY,
   studentId INT REFERENCES student (id),
   friend INT REFERENCES student (id)
);

CREATE TABLE artist(
   id SERIAL PRIMARY KEY,
   studentId INT REFERENCES student (id),
   friend INT REFERENCES student (id)
);

INSERT INTO student (age) VALUES (20); --Trying to remove this
INSERT INTO student (age) VALUES (21); --Trying to remove this
INSERT INTO engineer (studentId) VALUES (1);
INSERT INTO artist (studentId,friend) VALUES (2,1);

I don't want to have to type those two lines, therefore, I am using the below line

DROP SCHEMA PUBLIC CASCADE;
CREATE SCHEMA PUBLIC;

CREATE TABLE student(
   studentId SERIAL PRIMARY KEY,
   age INT
);

CREATE TABLE engineer(
   id SERIAL PRIMARY KEY,
   friend INT REFERENCES student (studentId)
) INHERITS (student);

CREATE TABLE artist(
   id SERIAL PRIMARY KEY,
   friend INT REFERENCES student (studentId)
) INHERITS (student);

INSERT INTO engineer (id,age) VALUES (DEFAULT,20);
INSERT INTO artist (id,age,friend) VALUES (DEFAULT,20,1);

But I get the following error.

psql:test.psql:45: ERROR:  insert or update on table "artist"     
violates foreign key constraint "artist_friend_fkey"
DETAIL:  Key (friend)=(1) is not present in table "student".

Is this yet another limitation to add to the long list of Postgres issues?

2 Answers 2

7

Yes. Look at docs Bottom Caveats section:

A serious limitation of the inheritance feature is that indexes (including unique constraints) and foreign key constraints only apply to single tables, not to their inheritance children

Sign up to request clarification or add additional context in comments.

3 Comments

Darth Vader Voice NOOOOOOOOOOOOoooooooooooooooooo
In facts, Postgres inheritance should be considered as a structural trait. Very useful because when a trait is modified, all the tables using it are updated as well.
@greg I don't speak Klingon =p care to dumb that down for me.
1

I think I found a workaround for this. I just moved the reference into the parent like so

DROP SCHEMA PUBLIC CASCADE;
CREATE SCHEMA PUBLIC;

CREATE TABLE student(
   studentId SERIAL PRIMARY KEY,
   age INT,
   friend INT REFERENCES student (studentId)
);

CREATE TABLE engineer(
   id SERIAL PRIMARY KEY
) INHERITS (student);

CREATE TABLE artist(
   id SERIAL PRIMARY KEY
) INHERITS (student);

INSERT INTO engineer (id,age) VALUES (DEFAULT,20);
INSERT INTO artist (id,age,friend) VALUES (DEFAULT,20,1);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.