Fix up query logic for handling delegates, so that it is more robust