I am facing the following problem: I need to create some kind of bill management system. There are bills and there are articles on said bills. Articles can be changed at a later date but they have to remain the way they were on bills that were already made. So far I was going with something like this:
CREATE TABLE article (
article_id INTEGER NOT NULL,
revision INTEGER NOT NULL,
PRIMARY KEY (article_id, revision)
);
CREATE TABLE bill (
bill_id INTEGER PRIMARY KEY
);
I went with an revision attribute to implement this. Every time an article gets updated, I'm going to create a new entry with the same id but with an incremented revision number. I also have a third table that references both the article and bill table. A bill can have multiple articles on it, but it shouldn't have more than one of the same article on it (so basically, bill 1 can have article A rev 0 and B rev 1 on it, but it can't have article A rev 0 and A rev 1 on it). I tried it this way:
CREATE TABLE contained (
bill_id INTEGER REFERENCES bill(bill_id),
FOREIGN KEY (article_id, revision) REFERENCES article(article_id, revision),
PRIMARY KEY (bill_id, article_id)
);
but it's obviously not working since I can't only use part of the referenced composite key in my primary key. Is there any way to get this to work or an easier alternative to get around this dilemma?
EDIT: changing the third table into
CREATE TABLE contained (
bill_id INTEGER REFERENCES bill(bill_id),
article_id INTEGER NOT NULL,
revision INTEGER NOT NULL,
FOREIGN KEY (article_id, revision) REFERENCES article(article_id, revision),
PRIMARY KEY (bill_id, article_id)
);
gives me yet another error:
ERROR: there is no unique constraint matching given keys for referenced table "bill"
which I kind of don't really understand either.