Refactor query sanitisation to make it safer and more maintainable.

Also, add tests.
This tag has no release notes.