Refactored code to utilise LAST_INSERT_ROWID