Rewrite query handling in a more idiomatic way