Improved logic to do an upsert if necessary,.