| | 1 | = Automatic deletion of product changes when the product is deleted |
| | 2 | |
| | 3 | === Description |
| | 4 | This trigger automatically deletes all change-history records associated with a product when that product is deleted. |
| | 5 | |
| | 6 | The CHANGE table stores information about modifications made to products. Since these records are dependent on the product they describe, they should not remain in the database after the corresponding product has been removed. |
| | 7 | |
| | 8 | This maintains referential and logical consistency between PRODUCT and CHANGE. |
| | 9 | |
| | 10 | ==== Tables involved |
| | 11 | - Product |
| | 12 | - Change |
| | 13 | - made_on |
| | 14 | |
| | 15 | ==== Type of trigger |
| | 16 | - BEFORE DELETE |
| | 17 | Activated on the `Product` table. |
| | 18 | |
| | 19 | ==== SQL Code |
| | 20 | {{{#!sql |
| | 21 | CREATE OR REPLACE FUNCTION delete_product_changes() |
| | 22 | RETURNS TRIGGER |
| | 23 | LANGUAGE plpgsql |
| | 24 | AS $$ |
| | 25 | BEGIN |
| | 26 | -- Delete all changes associated with the product |
| | 27 | DELETE FROM change |
| | 28 | WHERE product_code = OLD.code; |
| | 29 | |
| | 30 | RETURN OLD; |
| | 31 | END; |
| | 32 | $$; |
| | 33 | |
| | 34 | |
| | 35 | CREATE TRIGGER trg_delete_product_changes |
| | 36 | BEFORE DELETE |
| | 37 | ON product |
| | 38 | FOR EACH ROW |
| | 39 | EXECUTE FUNCTION delete_product_changes(); |
| | 40 | |
| | 41 | }}} |
| | 42 | |
| | 43 | === Logic explanation |
| | 44 | |
| | 45 | When a product is deleted, the trigger: |
| | 46 | |
| | 47 | **1.** Retrieves the product's code from OLD.code. |
| | 48 | **2.** Searches the CHANGE table for all records where product_code matches that code. |
| | 49 | **3.** Deletes those change-history records. |
| | 50 | **4.** Allows the original product deletion to continue. |
| | 51 | |
| | 52 | === Reason for trigger |
| | 53 | |
| | 54 | This trigger is useful because: |
| | 55 | |
| | 56 | - It prevents orphaned change records. |
| | 57 | - It keeps the CHANGE table consistent with PRODUCT. |
| | 58 | - It automatically performs cleanup when a product is deleted. |
| | 59 | - The application does not need to manually delete dependent records. |
| | 60 | - It centralizes deletion logic in the database. |