How to implement a database design where I can track changes made to specific columns
-
07-07-2021 - |
Question
How does one implement event tracking on the database side? Assume I have the following columns in a table: UserID, Column1, Column2, Column3 where UserID is the primary key and Column1 has a unique constraint.
Assume the user can change the values of Column1, Column2, and Column3 on the application side.
Further assume I need to detect changes that have been made to each column and display them to the user.
I thought of doing something like this:
Table1: EventID (PK), EventDate, UserID, Column1
Table2: EventID (PK), EventDate, UserID, Column2
Table3: EventID (PK), EventDate, UserID, Column3
There is no uniqueness validation on any of the above columns except of course for the primary key. This way, whenever each column is modified, I insert the new value to the appropriate table and can track all changes that have been made to the column, but this means I need to forgo the unique constraint on Column1. I can check uniqueness on the application layer by fetching the most recent Column1 values for each UserID and comparing them to each other. (Don't know how smart this is)
This also means I need to create a separate table for every column I need to track changes to.
Being a non-expert in database design, I want to know how I could implement a database architecture, in the most elegant way, where I can do event tracking.
P.S. If this helps any, I'm interested in using SQL Azure.
Solution
You should not need a whole table just to log events for each column of the application tables. Keep all the event logs
in one table. Define it like:
EventLogs
EventID (PK)
EventDate
UserID # remember to add an index
Field_changed # format: TableName.FieldName as a string
# or instead of Field_changed with both in one, you can do:
Table_changed
Column_changed
Depending on how many tables/actions/events you have and if you want to store before/after values, you could separate things out a little but it shouldn't be required.
As for tracking "specific columns", add that in the app code when Updates
are successful. Not sure how you plan to track Inserts
and Deletes
but if you want that too, add an Event_Type
(enum) field in the log table.