Fixes #3611: Refactored query caching.