Fix error where query could refer to wrong database