forked from ADB-course/20240819-20241125-adb-bbit2-2-classroom-semester-project-BBT3104-SemesterProject
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.sql
More file actions
86 lines (68 loc) · 2.34 KB
/
script.sql
File metadata and controls
86 lines (68 loc) · 2.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
-- Write your SQL code here
-- normal triggers
--trigger 1
DELIMITER //
CREATE TRIGGER check_stock_before_order
BEFORE INSERT ON Orders
FOR EACH ROW
BEGIN
DECLARE insufficient_stock BOOLEAN DEFAULT FALSE;
DECLARE ingredient_stock INT;
DECLARE done INT DEFAULT FALSE;
DECLARE cur CURSOR FOR
SELECT i.stock_level
FROM DishIngredients di
JOIN Ingredients i ON di.ingredient_id = i.ingredient_id
WHERE di.dish_id = NEW.dish_id;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
OPEN cur;
read_loop: LOOP
FETCH cur INTO ingredient_stock;
IF done THEN
LEAVE read_loop;
END IF;
-- Check if sufficient stock for each ingredient
IF ingredient_stock < (SELECT quantity FROM DishIngredients WHERE dish_id = NEW.dish_id AND ingredient_id = (SELECT ingredient_id FROM DishIngredients WHERE dish_id = NEW.dish_id LIMIT 1)) THEN
SET insufficient_stock = TRUE;
LEAVE read_loop;
END IF;
END LOOP;
CLOSE cur;
IF insufficient_stock THEN
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Insufficient stock for this order.';
END IF;
END; //
DELIMITER ;
--trigger 2
DELIMITER //
CREATE TRIGGER check_stock_before_order_update
BEFORE UPDATE ON Orders
FOR EACH ROW
BEGIN
DECLARE insufficient_stock BOOLEAN DEFAULT FALSE;
DECLARE ingredient_stock INT;
DECLARE done INT DEFAULT FALSE;
DECLARE cur CURSOR FOR
SELECT i.stock_level
FROM DishIngredients di
JOIN Ingredients i ON di.ingredient_id = i.ingredient_id
WHERE di.dish_id = NEW.dish_id;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
OPEN cur;
read_loop: LOOP
FETCH cur INTO ingredient_stock;
IF done THEN
LEAVE read_loop;
END IF;
-- Check if sufficient stock for each ingredient
IF ingredient_stock < (SELECT quantity FROM DishIngredients WHERE dish_id = NEW.dish_id AND ingredient_id = (SELECT ingredient_id FROM DishIngredients WHERE dish_id = NEW.dish_id LIMIT 1)) THEN
SET insufficient_stock = TRUE;
LEAVE read_loop;
END IF;
END LOOP;
CLOSE cur;
IF insufficient_stock THEN
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Insufficient stock for this order.';
END IF;
END; //
DELIMITER ;