Refactor the runQuery logic into a function