|
PostgreSQL: Advanced SQL: Rules
- Rewrite queries on the fly
- Useful for compatibility (updatable views, etc), auditing, journaling
01 CREATE [ OR REPLACE ] RULE name AS ON event
02 TO table [ WHERE condition ]
03 DO [ INSTEAD ] { NOTHING | command | ( command ; command ... ) }
- event = [ SELECT | INSERT | UPDATE | DELETE ]
- WHERE = usual where clause
- INSTEAD = do not execute the original query
- NOTHING = noop
- command = a new query
- For UPDATE and DELETE, NEW.* and OLD.*
- Example: Never delete data from a master table comb_t. Store changes else where
01 CREATE TABLE t (i int, primary key (i));
02 INSERT INTO t VALUES(1);
03 CREATE TABLE not_t(i int, primary key (i));
04 CREATE VIEW comb_t AS SELECT i FROM t EXCEPT SELECT i FROM not_t;
05 CREATE RULE t1 AS ON DELETE TO comb_t DO INSTEAD INSERT INTO not_t VALUES(OLD.i);
06 CREATE RULE t2 AS ON INSERT TO comb_t DO INSTEAD INSERT INTO t VALUES(NEW.i)
Page 29
|