protected function get_course_level_context_restriction_sql(\context $context = null,
            $coursetable, $paramtype = SQL_PARAMS_QM) {
        global $DB;

        if (!$context) {
            return ['', []];
        }

        switch ($paramtype) {
            case SQL_PARAMS_QM:
                $param1 = '?';
                $param2 = '?';
                $key1 = 0;
                $key2 = 1;
                break;
            case SQL_PARAMS_NAMED:
                $param1 = ':gclcrs0';
                $param2 = ':gclcrs1';
                $key1 = 'gclcrs0';
                $key2 = 'gclcrs1';
                break;
            default:
                throw new \coding_exception('Unexpected $paramtype: ' . $paramtype);
        }

        $params = [];
        switch ($context->contextlevel) {
            case CONTEXT_SYSTEM:
                $sql = '';
                break;

            case CONTEXT_COURSECAT:
                // Find all courses within the specified category or any sub-category.
                $pathmatch = $DB->sql_like('gclcrscc2.path',
                        $DB->sql_concat('gclcrscc1.path', $param2));
                $sql = " JOIN {course_categories} gclcrscc1 ON gclcrscc1.id = $param1
                         JOIN {course_categories} gclcrscc2 ON gclcrscc2.id = $coursetable.category
                              AND (gclcrscc2.id = gclcrscc1.id OR $pathmatch) ";
                $params[$key1] = $context->instanceid;
                // Note: This param is a bit annoying as it obviously never changes, but sql_like
                // throws a debug warning if you pass it anything with quotes in, so it has to be
                // a bound parameter.
                $params[$key2] = '/%';
                break;

            case CONTEXT_COURSE:
                // We just join again against the same course entry and confirm that it has the
                // same id as the context.
                $sql = " JOIN {course} gclcrsc ON gclcrsc.id = $coursetable.id
                              AND gclcrsc.id = $param1";
                $params[$key1] = $context->instanceid;
                break;

            case CONTEXT_BLOCK:
            case CONTEXT_MODULE:
            case CONTEXT_USER:
                // Context cannot contain any courses.
                return [null, null];

            default:
                throw new \coding_exception('Unexpected contextlevel: ' . $context->contextlevel);
        }

        return [$sql, $params];
    }