ᕼello! I think I have a somewhat tricky postgres situation:
parents have children. children have an age, and a flag that they are the appreciated.
The rule: a parent can't appreciate two children of the same age!
My question is: how to enforce this rule?
Current schema:
CREATE TABLE parent (
id SERIAL PRIMARY KEY,
name VARCHAR(50) NOT NULL
);
CREATE TABLE child (
id SERIAL PRIMARY KEY,
parent INTEGER REFERENCES parent(id) NOT NULL,
name VARCHAR(50) NOT NULL,
age INTEGER NOT NULL,
appreciated BOOLEAN NOT NULL
);
Put some values in:
INSERT INTO parent(name) VALUES
('bob'), -- assume bob's id = 0
('mary'); -- assume mary's id = 1
INSERT INTO child(parent, name, age, appreciated) VALUES
(0, 'child1', 10, FALSE), -- Bob has children 1, 2, 3
(0, 'child2', 10, FALSE),
(0, 'child3', 15, FALSE),
(1, 'child4', 20, FALSE), -- Mary has children 4, 5, 6
(1, 'child5', 20, FALSE),
(1, 'child6', 10, FALSE);
All fine so far. No child is appreciated, which is always valid.
Mary is allowed to appreciate child6:
UPDATE child SET appreciated=TRUE WHERE name='child6';
Bob is allowed to appreciate child2. child2 is the same age as child6 (who is already appreciated), but child6 is not Bob's child.
UPDATE child SET appreciated=TRUE WHERE name='child2';
Bob now cannot appreciate child1. This child1 is the same age as child2, and child2 is already appreciated.
UPDATE child SET appreciated=TRUE WHERE name='child2'; -- This needs to FAIL!
How do I enforce such a constraint? I'm open to all kinds of solutions, but modifying the general schema is not an option.
Thanks in advance!