MDL-12858 fix course category depths during upgrade to 1.9; merged from MOODLE_19_STABLE
authorskodak <skodak>
Wed, 19 Dec 2007 17:48:21 +0000 (17:48 +0000)
committerskodak <skodak>
Wed, 19 Dec 2007 17:48:21 +0000 (17:48 +0000)
lib/db/upgrade.php
lib/db/upgradelib.php

index bd28995cead29439401ddd425f54b4c9127bee12..41ab52e081933428115a0d6ccb03eaaaf507462f 100644 (file)
@@ -2055,10 +2055,7 @@ function xmldb_main_upgrade($oldversion=0) {
         $result = $result && create_table($table);
 
     /// make sure category depths, parents and paths are ok, categories from 1.5 may not be properly initialized (MDL-12585)
-        $sql = "UPDATE {$CFG->prefix}course_categories
-                   SET depth = 1, parent = 0, path = ".sql_concat("'/'", "id")."
-                 WHERE depth = 0 OR parent = 0";
-        execute_sql($sql); 
+        upgrade_fix_category_depths();
 
     /// Recalculate depths, paths and so on
         if (!empty($CFG->rolesactive)) {
index 2c038a76c747b3c8a522ca7140b4a0d0baf8d1b9..f27b7862f5854fd950b3020e07024c385e27e742 100644 (file)
@@ -514,4 +514,52 @@ function upgrade_18_groups_drop_keys_indexes() {
     return $result;
 }
 
+function upgrade_fix_category_depths() {
+    global $CFG, $db;
+
+    // first fix incorrect parents
+    $sql = "SELECT c.id
+              FROM {$CFG->prefix}course_categories c
+             WHERE c.parent > 0 AND c.parent NOT IN (SELECT pc.id FROM {$CFG->prefix}course_categories pc)";
+    if ($rs = get_recordset_sql($sql)) {
+        while ($cat = rs_fetch_next_record($rs)) {
+            $cat->depth  = 1;
+            $cat->path   = '/'.$cat->id;
+            $cat->parent = 0;
+            update_record('course_categories', $cat);
+        }
+        rs_close($rs);
+    }
+
+    // now add path and depth to top level categories
+    $sql = "UPDATE {$CFG->prefix}course_categories
+               SET depth = 1, path = ".sql_concat("'/'", "id")."
+             WHERE parent = 0";
+    execute_sql($sql);
+
+    // now fix all other levels - slow but works in all supported dbs
+    $parentdepth = 1;
+    $db->debug = true;
+    while (record_exists('course_categories', 'depth', 0)) {
+        $sql = "SELECT c.id, pc.path
+                  FROM {$CFG->prefix}course_categories c, {$CFG->prefix}course_categories pc
+                 WHERE c.parent=pc.id AND c.depth=0 AND pc.depth=$parentdepth";
+        if ($rs = get_recordset_sql($sql)) {
+            while ($cat = rs_fetch_next_record($rs)) {
+                $cat->depth = $parentdepth+1;
+                $cat->path  = $cat->path.'/'.$cat->id;
+                update_record('course_categories', $cat);
+            }
+            rs_close($rs);
+        }
+        $parentdepth++;
+        if ($parentdepth > 100) {
+            //something must have gone wrong - nobody can have more than 100 levels of categories, right?
+            debugging('Unknown error fixing category depths');
+            break;
+        }
+    }
+    $db->debug = true;
+}
+
 ?>