handle inserts/upserts correctly, could be cleaned up a bit