I want to ensure consistency and make sure only one phone line is the default for a house.
Schema: PhoneLine
ID | isDefault | HouseID
I want to add a trigger so that when you add/update a row, and set isDefault
to True
, all other rows in same table with the same HouseID
set isDefault
to False
.
I can't figure out a way to do this without creating a recursive mess.
What's the best way of approaching it?
I tried:
CREATE OR REPLACE FUNCTION unsetCurrentDefault()
RETURNS trigger AS $unsetCurrentDefault$
BEGIN
IF NEW.isdefault AND NEW.houseid IS NOT NULL THEN
-- Current ones get reset.
UPDATE phoneline SET isdefault = false
WHERE houseid = NEW.houseid AND id <> NEW.id AND isdefault;
END IF;
RETURN NEW;
END;
$unsetCurrentDefault$ LANGUAGE plpgsql;
CREATE TRIGGER updateDefaultValue AFTER INSERT OR UPDATE ON PhoneLine
FOR EACH ROW EXECUTE PROCEDURE unsetCurrentDefault();
But the behaviour seems recursive.
UNIQUE (houseID) WHERE (isDefault)
HouseID
(not with the sameID
). And it's confusing that the trigger is on a mysteriouspatienttable
...