Fix segfault, by using iterator to destroyed query