I am making a simple note app, and I want to create a table to track a note’s edit history and save them with an incrementing version as a composite key with the note’s id. So for example:
note_id | version | content
----------------------------
1 | 1 | some_text
1 | 2 | some_text
2 | 1 | some_text
2 | 2 | some_text
1 | 3 | some_text
3 | 1 | some_text
1 | 4 | some_text
The composite key is made up of note_id and version
I want to increment version for each note_id
Is there a way to automate this? I have seen some other posts, and experimented with triggers and functions, but I have not yet been able to get anything to work. Any advice is greatly appreciated!
2
Answers
Cool I actually got this to work, hopefully this can help someone else in the future. Thanks to this answer which I made some slight tweaks too, but mostly it just worked.
And for reference, here are my main tables
Keep in mind with this approach the id’s and versions have to be searched for each insert, so it’s good to have an index to speed that up. To avoid constant searches of the main table, you can maintain a table with latest
version
for eachnote_id
. The search still has to take place, but there’s less to search through: demoNow you can insert nothing or anything into the version column and the trigger will take care of it:
You need to formulate your own rules on what to do if someone comes in and deletes or updates something in the table, or remember not to rely on the continuity of version sequences – which is actually a good advice for any sequence due to caching and transaction behaviour.