| | 1 | = Prevention of deleting stores with existing orders or reports |
| | 2 | |
| | 3 | === Description |
| | 4 | This trigger prevents a store from being deleted if the store has existing orders or reports associated with it. |
| | 5 | |
| | 6 | A store should not be removed while historical business data still references it, because this could result in the loss of important information about sales, reports, and store activity. |
| | 7 | |
| | 8 | ==== Tables involved |
| | 9 | - Store |
| | 10 | - Report |
| | 11 | - Order |
| | 12 | - sells |
| | 13 | |
| | 14 | ==== Type of trigger |
| | 15 | - BEFORE DELETE |
| | 16 | |
| | 17 | Activated on the `Store` table. |
| | 18 | |
| | 19 | ==== SQL Code |
| | 20 | {{{#!sql |
| | 21 | CREATE OR REPLACE FUNCTION prevent_store_deletion() |
| | 22 | RETURNS TRIGGER |
| | 23 | LANGUAGE plpgsql |
| | 24 | AS $$ |
| | 25 | BEGIN |
| | 26 | -- Check whether the store has existing reports |
| | 27 | IF EXISTS ( SELECT 1 FROM report WHERE store_id = OLD.store_id ) THEN |
| | 28 | RAISE EXCEPTION 'Store % cannot be deleted because it has existing reports.', OLD.store_id; |
| | 29 | END IF; |
| | 30 | -- Check whether the store has products associated with it |
| | 31 | IF EXISTS ( SELECT 1 FROM sells WHERE store_id = OLD.store_id ) THEN |
| | 32 | RAISE EXCEPTION 'Store % cannot be deleted because it has existing product records.', OLD.store_id; |
| | 33 | END IF; |
| | 34 | RETURN OLD; |
| | 35 | END; |
| | 36 | $$; |
| | 37 | |
| | 38 | CREATE TRIGGER trg_prevent_store_deletion |
| | 39 | BEFORE DELETE |
| | 40 | ON store |
| | 41 | FOR EACH ROW |
| | 42 | EXECUTE FUNCTION prevent_store_deletion(); |
| | 43 | |
| | 44 | }}} |
| | 45 | |
| | 46 | === Logic explanation |
| | 47 | |
| | 48 | Before a store is deleted, the trigger: |
| | 49 | |
| | 50 | **1.** Identifies the store using OLD.store_id. |
| | 51 | **2.** Checks whether the store has any reports in the REPORT table. |
| | 52 | **3.** Checks whether the store has any products associated with it through sells. |
| | 53 | **4.** If any historical records exist, the deletion is rejected. |
| | 54 | **5.** If no dependent records exist, the deletion is allowed. |
| | 55 | |
| | 56 | === Reason for trigger |
| | 57 | |
| | 58 | This trigger is useful because: |
| | 59 | |
| | 60 | - It protects historical business data. |
| | 61 | - It prevents accidental deletion of stores with existing records. |
| | 62 | - It maintains referential and business data integrity. |
| | 63 | - It ensures that important reports and sales history are not lost. |