Initial work on rewriting the query engine.

This is part of Tori 3.0-dev.