Make Query more object-oriented

Change several module-level functions into methods and move data from flask.g into a Query instance.