1 | CREATE OR REPLACE FUNCTION trg_validate_preorder_price()
|
---|
2 | RETURNS TRIGGER AS $$
|
---|
3 | DECLARE
|
---|
4 | v_menu_price NUMERIC;
|
---|
5 | v_restaurant_id INTEGER;
|
---|
6 | BEGIN
|
---|
7 | SELECT restaurantid INTO v_restaurant_id
|
---|
8 | FROM reservations
|
---|
9 | WHERE reservationid = NEW.reservation_id;
|
---|
10 |
|
---|
11 | IF NOT FOUND THEN
|
---|
12 | RAISE EXCEPTION 'Reservation ID % not found', NEW.reservation_id;
|
---|
13 | END IF;
|
---|
14 |
|
---|
15 | SELECT price INTO v_menu_price
|
---|
16 | FROM menus
|
---|
17 | WHERE item_name = NEW.name AND restaurant_id = v_restaurant_id;
|
---|
18 |
|
---|
19 | IF NOT FOUND THEN
|
---|
20 | RAISE EXCEPTION 'Menu item "%" not found for restaurant ID %', NEW.name, v_restaurant_id;
|
---|
21 | END IF;
|
---|
22 |
|
---|
23 | IF NEW.quantity <= 0 THEN
|
---|
24 | RAISE EXCEPTION 'Invalid quantity for item "%": must be greater than 0', NEW.name;
|
---|
25 | END IF;
|
---|
26 |
|
---|
27 | IF NEW.price <> v_menu_price THEN
|
---|
28 | RAISE EXCEPTION 'Price mismatch for item "%": expected %, got %',
|
---|
29 | NEW.name, v_menu_price, NEW.price;
|
---|
30 | END IF;
|
---|
31 |
|
---|
32 | RETURN NEW;
|
---|
33 | END;
|
---|
34 | $$ LANGUAGE plpgsql;
|
---|
35 |
|
---|
36 |
|
---|
37 | DROP TRIGGER IF EXISTS validate_preorder_price_trigger ON reservation_preordered_items;
|
---|
38 |
|
---|
39 | CREATE TRIGGER validate_preorder_price_trigger
|
---|
40 | BEFORE INSERT OR UPDATE ON reservation_preordered_items
|
---|
41 | FOR EACH ROW
|
---|
42 | EXECUTE FUNCTION trg_validate_preorder_price();
|
---|
43 |
|
---|
44 | INSERT INTO reservation_preordered_items (reservation_id, preordered_item_name, quantity, price_at_order)
|
---|
45 | VALUES (22, 'California Roll', 1, 5.99); --reservationId mismatch
|
---|
46 |
|
---|
47 | INSERT INTO reservation_preordered_items (reservation_id, preordered_item_name, quantity, price_at_order)
|
---|
48 | VALUES (21, 'California Roll', 1, 5.99); --price mismatch
|
---|
49 |
|
---|
50 | INSERT INTO reservation_preordered_items (reservation_id, preordered_item_name, quantity, price_at_order)
|
---|
51 | VALUES (21, 'Roll', 1, 8.99); --name mismatch
|
---|
52 |
|
---|
53 | INSERT INTO reservation_preordered_items (reservation_id, preordered_item_name, quantity, price_at_order)
|
---|
54 | VALUES (21, 'California Roll', 0, 8.99); --quantity mismatch
|
---|
55 |
|
---|
56 | INSERT INTO reservation_preordered_items (reservation_id, preordered_item_name, quantity, price_at_order)
|
---|
57 | VALUES (21, 'California Roll', 1, 8.99); --works |
---|