Fix a bunch of bugs in the new query building