Created
November 9, 2009 00:15
-
-
Save eight/229566 to your computer and use it in GitHub Desktop.
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
-- PostgreSQLのルールシステムを使った論理削除の例 | |
-- 削除フラグと削除日時を保持するフィールドを持ったテーブルを作成 | |
CREATE TABLE a( | |
id serial PRIMARY KEY, | |
value text, | |
deleted boolean DEFAULT False, | |
deleted_on timestamp DEFAULT 'infinity' | |
); | |
-- DELETEが実行されたら代わりに削除フラグを立てて削除日時をセットするルール | |
CREATE RULE a_delete_rule AS ON DELETE TO a | |
DO INSTEAD | |
UPDATE a SET deleted=True, deleted_on=CURRENT_TIMESTAMP | |
WHERE id = OLD.id; | |
-- ここからはテストデータを投入、削除 | |
-- 三件件挿入 | |
INSERT INTO a(value) VALUES('a'); | |
INSERT INTO a(value) VALUES('b'); | |
INSERT INTO a(value) VALUES('c'); | |
-- 確認 | |
SELECT * FROM a; | |
-- 削除してみる | |
DELETE FROM a WHERE id>1; | |
-- 確認 削除されないで、削除フラグと削除日時が更新されている | |
SELECT * FROM a; | |
-- 後始末 | |
DROP TABLE a; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment