cache query function, and some refactoring