Add function to perform a custom query

This is also used by the other functions to perform their queries