refactoring query engine