refacotring upsert code