refactor generate method in order to make just one query