MDL-63686 core: Preload parent contexts

This commit is contained in:
Andrew Nicols
2019-01-08 14:11:00 +08:00
parent 38a1b4f203
commit ccbdced987
2 changed files with 73 additions and 0 deletions
+32
View File
@@ -5434,6 +5434,9 @@ abstract class context extends stdClass implements IteratorAggregate {
return array();
}
// Preload the contexts to reduce DB calls.
context_helper::preload_contexts_by_id($contextids);
$result = array();
foreach ($contextids as $contextid) {
$parent = context::instance_by_id($contextid, MUST_EXIST);
@@ -5870,6 +5873,35 @@ class context_helper extends context {
context::preload_from_record($rec);
}
/**
* Preload a set of contexts using their contextid.
*
* @param array $contextids
*/
public static function preload_contexts_by_id(array $contextids) {
global $DB;
// Determine which contexts are not already cached.
$tofetch = [];
foreach ($contextids as $contextid) {
if (!self::cache_get_by_id($contextid)) {
$tofetch[] = $contextid;
}
}
if (count($tofetch) > 1) {
// There are at least two to fetch.
// There is no point only fetching a single context as this would be no more efficient than calling the existing code.
list($insql, $inparams) = $DB->get_in_or_equal($tofetch, SQL_PARAMS_NAMED);
$ctxs = $DB->get_recordset_select('context', "id {$insql}", $inparams, '',
\context_helper::get_preload_record_columns_sql('{context}'));
foreach ($ctxs as $ctx) {
self::preload_from_record($ctx);
}
$ctxs->close();
}
}
/**
* Preload all contexts instances from course.
*