-
Notifications
You must be signed in to change notification settings - Fork 1
/
constraint.sql
75 lines (67 loc) · 1.79 KB
/
constraint.sql
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
--------------------------------------------------
--- Integrity Constraints
--------------------------------------------------
CREATE OR REPLACE FUNCTION trigger_category()
RETURNS TRIGGER
LANGUAGE plpgsql
AS $$
BEGIN
IF NEW.category = NEW.super_category THEN
RAISE EXCEPTION 'Category cannot contain itself.';
END IF;
RETURN NEW;
END;
$$;
CREATE TRIGGER category
BEFORE INSERT OR UPDATE
ON has_other
FOR EACH ROW
EXECUTE PROCEDURE trigger_category();
--------------------------------------------------
CREATE FUNCTION trigger_replenishment_units()
RETURNS TRIGGER
LANGUAGE plpgsql
AS $$
BEGIN
IF EXISTS (
SELECT planogram.units
FROM planogram
WHERE NEW.ean = planogram.ean
AND NEW.nro = planogram.nro
AND NEW.serial_number = planogram.serial_number
AND NEW.manufacturer = planogram.manufacturer
AND NEW.units > planogram.units) THEN
RAISE EXCEPTION 'Replenishment units cannot be more than planogram units.';
END IF;
RETURN NEW;
END;
$$;
CREATE TRIGGER replenishment_units
BEFORE INSERT OR UPDATE
ON replenishment_event
FOR EACH ROW
EXECUTE PROCEDURE trigger_replenishment_units();
--------------------------------------------------
CREATE FUNCTION trigger_product_on_shelf()
RETURNS TRIGGER
LANGUAGE plpgsql
AS $$
BEGIN
IF NOT EXISTS (
SELECT *
FROM product
LEFT JOIN has_category ON product.ean = has_category.ean
JOIN shelf ON shelf.name = product.cat OR shelf.name = has_category.name
WHERE NEW.nro = shelf.nro
AND NEW.serial_number = shelf.serial_number
AND NEW.manufacturer = shelf.manufacturer) THEN
RAISE EXCEPTION 'Shelf must contain category of product.';
END IF;
RETURN NEW;
END;
$$;
CREATE TRIGGER product_on_shelf
BEFORE INSERT OR UPDATE
ON replenishment_event
FOR EACH ROW
EXECUTE PROCEDURE trigger_product_on_shelf();