Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
647 views
in Technique[技术] by (71.8m points)

postgresql trigger after insert or update or delete

I have table called mdl_user and I added a new columns for this table, the first one is called "LastOperation" and the second one "TimeStamp"

I need to create trigger after insert or update or delete and write the output as "I" or "U" or "D" at "LastOperation" column and the time when this action happenes at "TimeStamp" column

NOTE: All this stuff to be in the same table not to be triggered for another table


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can get what you want and still use standard DML (including delete). It does however require a little behind the scenes manipulation of database objects. What it involves doing your DML against not a table but an update-able view.

  1. Add the new columns as usual to the table.
  2. Rename the table. Say to mdl_user_tab.
  3. Create a VIEW with the same name and definition as the old table. Simple select (no join) from new table name.
  4. Create a trigger function which interprets the DML manipulates the actual table.
  5. Create an INSTEAD trigger for all DML operations against the VIEW.

You now process everything against the view (most existing code will not require updating). But you may need some additional functionality for actually processing the table. See example here.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.6k users

...