Reputation: 6459
I have teams that can be assigned team members and people. The team table and person tables already exist and can't be touched, I'm creating join tables to assign team members and team leads.
I have one key constraint, a team lead must be a team member, and as long as someone is assigned as a team lead it should be impossible to remove them as a team member.
My sql looks something like this (translating from a more complex table, forgive me if I mistyped my example since I'm writing it by hand)
CREATE TABLE TEAM_MEMBERS (id BIGINT NOT NULL,
teamId BIGINT NOT NULL,
personId BIGINT NOT NULL,
PRIMARY KEY (id),
KEY (teamId),
KEY (personId)
CONSTRAINT fk_team FOREIGN KEY (teamId) REFERENCES TEAM(id) ON DELETE CASCADE);
CREATE TABLE TEAM_LEAD (id BIGINT NOT NULL,
teamId BIGINT NOT NULL,
personId BIGINT NOT NULL,
PRIMARY KEY (id),
KEY (teamId),
KEY (personId),
CONSTRAINT fk_team_u FOREIGN KEY (teamId) REFERENCES TEAM (id) ON DELETE CASCADE,
CONSTRAINT fk_child FOREIGN KEY (teamId, personId) REFERENCES TEAM_MEMBERS(teamId, personId)) ON DELETE RESTRICT;
This does not work. When a team is removed I get a constraint violation, because it cascades the delete to team_members first, attempts to delete that, and discovers that team_lead is blocking it.
My question, is there an easy way express some sort of order of operations here, to make sql understand that it should remove the team-lead first, or otherwise understand that it is not a constraint violation if it cascades the deletes entirely?
I realize one solution would be to make teamLead a boolean on team_members rather then a separate join table. For various reasons I would prefer not to do this, but it can be done if there is not another cleaner solution.
Were using PostgreSQL on server, H2 for our testing, though we would prefer not to be tied in to a DB if possible.
Upvotes: 1
Views: 909
Reputation: 2180
This SQL constraint should not be here:
CONSTRAINT fk_child FOREIGN KEY (teamId, personId) REFERENCES TEAM_MEMBERS(teamId, personId)) ON DELETE RESTRICT;
Your data model seems wrong: a team leader should not have a foreign key pointing to team members, but to a team only.
Could you please post the complete schema so we could provide a more complete answer?
Upvotes: 1