Massive refactoring to support local queries