r8904: Split off the query stage as a separate function.