perform atomic operations on elements inside a container
0
votes
2
answers
217
views
In my DB Tshirts, Jeans and Shoes can be placed inside a Box and they can have a color that may be null.
Elements of the box must have the same color. To ensure this I use a trigger:
/*
If I try to INSERT (OR UPDATE) an item in a box
containing elements of different color, it raises an exception.
*/
BEGIN
IF (
SELECT color FROM tshirt WHERE tshirt.box_id = NEW.box_id
UNION SELECT color FROM jeans WHERE jeans.box_id = NEW.box_id
UNION SELECT color FROM shoes WHERE shoes.box_id = NEW.box_id
) NEW.color THEN
RAISE EXCEPTION 'Error..';
RETURN NULL;
END IF;
END;
Suppose I want to change the color from 'Blue' to 'Red' for items inside Box 1. This code will fail because of the trigger:
UPDATE Tshirts SET color = 'Red' WHERE box_id = 1;
UPDATE Jeans SET color = 'Red' WHERE box_id = 1;
UPDATE Shoes SET color = 'Red' WHERE box_id = 1;
The only way I can change the color of items in the box is:
1. Remove all items from the box, setting their box_id to null.
2. Change the color of all the elements.
3. Put all the elements inside the box, setting back their box_id.
How can I change the color of items in a box more simply and atomically through modeling or triggers?

Asked by Yata
(33 rep)
Oct 16, 2015, 12:56 PM
Last activity: Jul 10, 2025, 01:28 PM
Last activity: Jul 10, 2025, 01:28 PM