prevent NULL contents before field change (old servers can have this wrongly defined...
[moodle.git] / lib / db / upgradelib.php
CommitLineData
42ff9ce6 1<?php //$Id$
2
3/*
4 * This file is used for special upgrade functions - for example groups and gradebook.
56a1a882 5 * These functions must use SQL and database related functions only- no other Moodle API,
42ff9ce6 6 * because it might depend on db structures that are not yet present during upgrade.
7 * (Do not use functions from accesslib.php, grades classes or group functions at all!)
8 */
9
863850d2 10function upgrade_fix_category_depths() {
11 global $CFG, $db;
12
13 // first fix incorrect parents
14 $sql = "SELECT c.id
15 FROM {$CFG->prefix}course_categories c
16 WHERE c.parent > 0 AND c.parent NOT IN (SELECT pc.id FROM {$CFG->prefix}course_categories pc)";
17 if ($rs = get_recordset_sql($sql)) {
18 while ($cat = rs_fetch_next_record($rs)) {
19 $cat->depth = 1;
20 $cat->path = '/'.$cat->id;
21 $cat->parent = 0;
22 update_record('course_categories', $cat);
23 }
24 rs_close($rs);
25 }
26
27 // now add path and depth to top level categories
28 $sql = "UPDATE {$CFG->prefix}course_categories
29 SET depth = 1, path = ".sql_concat("'/'", "id")."
30 WHERE parent = 0";
31 execute_sql($sql);
32
33 // now fix all other levels - slow but works in all supported dbs
34 $parentdepth = 1;
35 $db->debug = true;
36 while (record_exists('course_categories', 'depth', 0)) {
37 $sql = "SELECT c.id, pc.path
38 FROM {$CFG->prefix}course_categories c, {$CFG->prefix}course_categories pc
39 WHERE c.parent=pc.id AND c.depth=0 AND pc.depth=$parentdepth";
40 if ($rs = get_recordset_sql($sql)) {
41 while ($cat = rs_fetch_next_record($rs)) {
42 $cat->depth = $parentdepth+1;
43 $cat->path = $cat->path.'/'.$cat->id;
44 update_record('course_categories', $cat);
45 }
46 rs_close($rs);
47 }
48 $parentdepth++;
49 if ($parentdepth > 100) {
50 //something must have gone wrong - nobody can have more than 100 levels of categories, right?
51 debugging('Unknown error fixing category depths');
52 break;
53 }
54 }
55 $db->debug = true;
56}
57
42ff9ce6 58?>