Thanks to my colleague Deepak, today I learnt a new thing. If you want a column in your table like lastModifiedTime that gets inserted when the row is created and also auto updated whenever someone updates the row then traditionally the only way to do this was to use a trigger. I have used oracle for 4-5 years so I thought this is not possible to do in DDL and the trigger is the only way. But Mysql has this magic. You can create a column like
lastModifiedTime TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
And this column will have current datetime on insert and will get updated with current datetime anytime a mutation to that row occurs. Wow no more triggers and this column is self maintained so no more worry about some dba disabling the trigger and did the update to get data inserted quickly.
lastModifiedTime TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
And this column will have current datetime on insert and will get updated with current datetime anytime a mutation to that row occurs. Wow no more triggers and this column is self maintained so no more worry about some dba disabling the trigger and did the update to get data inserted quickly.
Hey I am trying to do something similar but I have a more detailed audit trail - lastModifiedDate, createdDate, lastModifiedByUser, createdByUser, isActive. Any ideas on how to program triggers for the users as well ?
ReplyDeletewell for lastModifiedByUser you cant do it by trigger because you have to pass that from the application. I man your app can have a user called as kpatel who modified the record but all mysql knows is the user with whom you are connecting to the database so you have to manually do this at the application layer may be using AOP or manually.
ReplyDelete