public function add_from_sql(string $sql, array $params) : contextlist {
        global $DB;

        $fields = \context_helper::get_preload_record_columns_sql('ctx');
        if ($fieldname = $this->guess_id_field_from_sql($sql)) {
            if (is_numeric($fieldname)) {
                $wrapper = "
                  SELECT {$fields}
                    FROM {context} ctx
                   WHERE ctx.id = :fieldvalue";
                $params = ['fieldvalue' => $fieldname];
            } else {
                // Able to guess a field name.
                $wrapper = "
                  SELECT {$fields}
                    FROM {context} ctx
                    JOIN ({$sql}) target ON ctx.id = target.{$fieldname}";
            }
        } else {
            // No field name available. Fall back on a potentially slower version.
            $wrapper = "
              SELECT {$fields}
                FROM {context} ctx
               WHERE ctx.id IN ({$sql})";
        }
        $contexts = $DB->get_recordset_sql($wrapper, $params);

        $contextids = [];
        foreach ($contexts as $context) {
            $contextids[] = $context->ctxid;
            \context_helper::preload_from_record($context);
        }
        $contexts->close();

        $this->set_contextids(array_merge($this->get_contextids(), $contextids));

        return $this;
    }