Last active
July 24, 2023 06:04
-
-
Save crshmk/1e8c7ce08def2bf9400e2687c8fbb2e1 to your computer and use it in GitHub Desktop.
mysql row expiry strategy
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CREATE TABLE things ( | |
id int NOT NULL AUTO_INCREMENT PRIMARY KEY, | |
created timestamp NULL DEFAULT CURRENT_TIMESTAMP, | |
str varchar(10), | |
expires timestamp | |
); | |
INSERT INTO things (str) VALUES ('one'); | |
CREATE TRIGGER set_thing_expires | |
BEFORE INSERT ON things | |
FOR EACH ROW | |
SET NEW.expires = ADDDATE(CURRENT_TIMESTAMP, INTERVAL 30 DAY); | |
INSERT INTO things (str) VALUES ('two'); | |
SELECT * FROM things; | |
+----+---------------------+------+---------------------+ | |
| id | created | str | expires | | |
+----+---------------------+------+---------------------+ | |
| 1 | 2023-07-23 15:11:53 | one | NULL | | |
| 2 | 2023-07-23 15:11:53 | two | 2023-08-22 15:11:53 | | |
+----+---------------------+------+---------------------+ | |
SELECT now(); | |
+---------------------+ | |
| now() | | |
+---------------------+ | |
| 2023-07-23 15:12:02 | | |
+---------------------+ | |
SELECT id FROM things WHERE expires > now(); | |
+----+ | |
| id | | |
+----+ | |
| 2 | | |
+----+ | |
DROP TRIGGER set_thing_expires; | |
CREATE TRIGGER set_thing_expires | |
BEFORE INSERT ON things | |
FOR EACH ROW | |
SET NEW.expires = ADDDATE(curdate(), INTERVAL 30 DAY); | |
INSERT INTO things (str) VALUES ('three'); | |
SELECT * FROM things; | |
+----+---------------------+-------+---------------------+ | |
| id | created | str | expires | | |
+----+---------------------+-------+---------------------+ | |
| 1 | 2023-07-23 15:11:53 | one | NULL | | |
| 2 | 2023-07-23 15:11:53 | two | 2023-08-22 15:11:53 | | |
| 3 | 2023-07-23 15:12:47 | three | 2023-08-22 00:00:00 | | |
+----+---------------------+-------+---------------------+ | |
/* renew item; update expiry to thirty days from renewal action */ | |
UPDATE things SET expires=ADDDATE(curdate(), INTERVAL 30 DAY) WHERE id=3; | |
SELECT things.*, UNIX_TIMESTAMP(things.expires) AS expires_stamp FROM things; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment