From d2e3a1b4f9c1f568a23d972402f4c5747b5f73cb Mon Sep 17 00:00:00 2001 From: Dan Marsden Date: Mon, 19 Mar 2012 14:50:59 +1300 Subject: [PATCH] MDL-27368 Clean up invalid course completion records keep oldest timestamps from all records --- lib/db/upgrade.php | 37 +++++++++++++++++++++++++++++++++++++ version.php | 2 +- 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/lib/db/upgrade.php b/lib/db/upgrade.php index c74c7248216..d2d71489e95 100644 --- a/lib/db/upgrade.php +++ b/lib/db/upgrade.php @@ -648,5 +648,42 @@ function xmldb_main_upgrade($oldversion) { upgrade_main_savepoint(true, 2012052100.00); } + if ($oldversion < 2012052500.01) { // fix invalid course_completion_records MDL-27368 + //first get all instances of duplicate records + $sql = 'SELECT userid, course FROM {course_completions} WHERE (deleted IS NULL OR deleted <> 1) GROUP BY userid, course HAVING (count(id) > 1)'; + $duplicates = $DB->get_recordset_sql($sql, array()); + + foreach ($duplicates as $duplicate) { + $pointer = 0; + //now get all the records for this user/course + $sql = 'userid = ? AND course = ? AND (deleted IS NULL OR deleted <> 1)'; + $completions = $DB->get_records_select('course_completions', $sql, + array($duplicate->userid, $duplicate->course), 'timecompleted DESC, timestarted DESC'); + $needsupdate = false; + $origcompletion = null; + foreach ($completions as $completion) { + $pointer++; + if ($pointer === 1) { //keep 1st record but delete all others. + $origcompletion = $completion; + } else { + //we need to keep the "oldest" of all these fields as the valid completion record. + $fieldstocheck = array('timecompleted', 'timestarted', 'timeenrolled'); + foreach ($fieldstocheck as $f) { + if ($origcompletion->$f > $completion->$f) { + $origcompletion->$f = $completion->$f; + $needsupdate = true; + } + } + $DB->delete_records('course_completions', array('id'=>$completion->id)); + } + } + if ($needsupdate) { + $DB->update_record('course_completions', $origcompletion); + } + } + + // Main savepoint reached + upgrade_main_savepoint(true, 2012052500.01); + } return true; } diff --git a/version.php b/version.php index f9992a16395..9a4c454f1f9 100644 --- a/version.php +++ b/version.php @@ -30,7 +30,7 @@ defined('MOODLE_INTERNAL') || die(); -$version = 2012052500.00; // YYYYMMDD = weekly release date of this DEV branch +$version = 2012052500.01; // YYYYMMDD = weekly release date of this DEV branch // RR = release increments - 00 in DEV branches // .XX = incremental changes