This would have to be duplicated in several places, so it has been moved to the replace_or_add_query method.