Separate the query builder into function

This way it's possible to use it by other modules.