Major refactoring and optimizations to the query engine.