Refactored query plan building