Database Triggers
SQL statements that are AUTOMATICALLY RUN when a specific table is changed
CREATE TRIGGER trigger_name
trigger_time trigger_event ON table_name FOR EACH ROW
BEGIN
...
END;
BEFORE
AFTER
INSERT
UPDATE
DELETE
photos
users
A Simple Validation
DELIMITER $$
CREATE TRIGGER must_be_adult
BEFORE INSERT ON users FOR EACH ROW
BEGIN
IF NEW.age < 18
THEN
SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT = 'Must be an adult!';
END IF;
END;
$$
DELIMITER ;
DELIMITER $$
CREATE TRIGGER must_be_adult
BEFORE INSERT ON people FOR EACH ROW
BEGIN
IF NEW.age < 18
THEN
SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT = 'Must be an adult!';
END IF;
END;
$$
DELIMITER ;
Refers to data that is about to be inserted
DELIMITER $$
CREATE TRIGGER must_be_adult
BEFORE INSERT ON people FOR EACH ROW
BEGIN
IF NEW.age < 18
THEN
SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT = 'Must be an adult!';
END IF;
END;
$$
DELIMITER ;
A numeric error code (1146). This number is MySQL-specific
A five-character SQLSTATE value ('42S02').
The values are taken from ANSI SQL and ODBC and are more standardized.
A message string - textual description of the error
Do something to cause an error, like...
SELECT * FROM kjhsadkjhas;
ERROR 1146 (42S02): Table 'ig_clone.kjhsadkjhas' doesn't exist
DELIMITER $$
CREATE TRIGGER must_be_adult
BEFORE INSERT ON people FOR EACH ROW
BEGIN
IF NEW.age < 18
THEN
SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT = 'Must be an adult!';
END IF;
END;
$$
DELIMITER ;
A generic state representing "unhandled user-defined exception"
DELIMITER $$
CREATE TRIGGER must_be_adult
BEFORE INSERT ON people FOR EACH ROW
BEGIN
IF NEW.age < 18
THEN
SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT = 'Must be an adult!';
END IF;
END;
$$
DELIMITER ;
Preventing Self-Follows
DELIMITER $$
CREATE TRIGGER trigger_name
trigger_time trigger_event ON table_name FOR EACH ROW
BEGIN
END;
$$
DELIMITER ;
Starter Code
Preventing Self-Follows
DELIMITER $$
CREATE TRIGGER example_cannot_follow_self
BEFORE INSERT ON follows FOR EACH ROW
BEGIN
IF NEW.follower_id = NEW.following_id
THEN
SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT = 'Cannot follow yourself, silly';
END IF;
END;
$$
DELIMITER ;
Logging Unfollows
DELIMITER $$
CREATE TRIGGER trigger_name
trigger_time trigger_event ON table_name FOR EACH ROW
BEGIN
END;
$$
DELIMITER ;
Starter Code
Logging Unfollows
DELIMITER $$
CREATE TRIGGER create_unfollow
AFTER DELETE ON follows FOR EACH ROW
BEGIN
INSERT INTO unfollows
SET follower_id = OLD.follower_id,
followee_id = OLD.followee_id;
END$$
DELIMITER ;
SHOW TRIGGERS;
DROP TRIGGER trigger_name;
Triggers can make debugging hard!