Move sql queries out to utils (to aid with testing)
Add tests for #7947 and fixed another bug that revealed itself.