From 5d62223bf0513d1cc3ed0ecdc4fa47dda2d1797e Mon Sep 17 00:00:00 2001
From: sam marshall <s.marshall@open.ac.uk>
Date: Thu, 2 Sep 2021 13:42:58 +0100
Subject: [PATCH] MDL-72025 Upgrade: Out of memory when updating social profile
 fields

---
 user/profile/field/social/upgradelib.php | 11 ++++++++---
 1 file changed, 8 insertions(+), 3 deletions(-)

diff --git a/user/profile/field/social/upgradelib.php b/user/profile/field/social/upgradelib.php
index 23387180ef8..37d1b1aa62b 100644
--- a/user/profile/field/social/upgradelib.php
+++ b/user/profile/field/social/upgradelib.php
@@ -145,8 +145,11 @@ function user_profile_social_create_profilefield($social) {
  */
 function user_profile_social_update_module_availability() {
     global $DB;
-    $modules = $DB->get_records('course_modules');
-    foreach ($modules as $mod) {
+    // Use transaction to improve performance if there are many individual database updates.
+    $transaction = $DB->start_delegated_transaction();
+    // Query all the course_modules entries that have availability set.
+    $rs = $DB->get_recordset_select('course_modules', 'availability IS NOT NULL', [], '', 'id, availability');
+    foreach ($rs as $mod) {
         if (isset($mod->availability)) {
             $availability = json_decode($mod->availability);
             if (!is_null($availability)) {
@@ -159,6 +162,8 @@ function user_profile_social_update_module_availability() {
             }
         }
     }
+    $rs->close();
+    $transaction->allow_commit();
 }
 
 /**
@@ -184,4 +189,4 @@ function user_profile_social_update_availability_structure(&$structure) {
             }
         }
     }
-}
\ No newline at end of file
+}