Better upsert implementation