Changes between Initial Version and Version 1 of Trigger4


Ignore:
Timestamp:
08/21/26 07:48:40 (27 hours ago)
Author:
235018
Comment:

--

Legend:

Unmodified
Added
Removed
Modified
  • Trigger4

    v1 v1  
     1= Automatic deletion of product changes when the product is deleted
     2
     3=== Description
     4This trigger automatically deletes all change-history records associated with a product when that product is deleted.
     5
     6The 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
     8This 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
     17Activated on the `Product` table.
     18
     19==== SQL Code
     20{{{#!sql
     21CREATE OR REPLACE FUNCTION delete_product_changes()
     22RETURNS TRIGGER
     23LANGUAGE plpgsql
     24AS $$
     25BEGIN
     26    -- Delete all changes associated with the product
     27    DELETE FROM change
     28    WHERE product_code = OLD.code;
     29
     30    RETURN OLD;
     31END;
     32$$;
     33
     34
     35CREATE TRIGGER trg_delete_product_changes
     36BEFORE DELETE
     37ON product
     38FOR EACH ROW
     39EXECUTE FUNCTION delete_product_changes();
     40
     41}}}
     42
     43=== Logic explanation
     44
     45When 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
     54This 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.