Moved all query-related state tracking and management into a separate class. This allows for new query types to be added in the future, and makes less dodgy assumptions about the current state when beginning or ending a query.