Refactoring broken upsert code