factor out code for creating or updating rows on insert