Last active
February 10, 2016 10:08
-
-
Save dre1080/377a396e7905920247d1 to your computer and use it in GitHub Desktop.
Soft-deletable records in Postgres
This file contains 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 FUNCTION soft_delete() | |
RETURNS trigger AS $$ | |
BEGIN | |
EXECUTE 'UPDATE ' | |
|| TG_TABLE_NAME | |
|| ' SET deleted_at = current_timestamp WHERE id = $1' | |
USING OLD.id; | |
RETURN OLD; | |
END; | |
$$ LANGUAGE plpgsql | |
-- CREATE A TABLE | |
CREATE TABLE table_name ( | |
id integer, | |
deleted_at timestamptz | |
); | |
-- CREATE A VIEW OF THAT TABLE | |
CREATE VIEW active_table_name AS | |
SELECT * FROM table_name WHERE deleted_at IS NULL; | |
-- CREATE A TRIGGER TO REPLACE DEFAULT DELETE | |
CREATE TRIGGER soft_delete_table_name | |
INSTEAD OF DELETE ON active_table_name | |
FOR EACH ROW EXECUTE PROCEDURE soft_delete(); | |
-- QUERIES SHOULD NOW BE RUN AGAINST `active_table_name` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment