2 // This file is part of Moodle - http://moodle.org/
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 * Upgrade helper functions
20 * @package mod_feedback
21 * @copyright 2016 Marina Glancy
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 defined('MOODLE_INTERNAL') || die();
28 * Fill new field courseid in tables feedback_completed or feedback_completedtmp
30 * @param bool $tmp use for temporary table
32 function mod_feedback_upgrade_courseid($tmp = false) {
34 $suffix = $tmp ? 'tmp' : '';
36 // Part 1. Ensure that each completed record has associated values with only one courseid.
38 FROM {feedback_completed$suffix} c, {feedback_value$suffix} v
39 WHERE c.id = v.completed
41 having count(DISTINCT v.course_id) > 1";
42 $problems = $DB->get_fieldset_sql($sql);
43 foreach ($problems as $problem) {
44 $courses = $DB->get_fieldset_sql("SELECT DISTINCT course_id "
45 . "FROM {feedback_value$suffix} WHERE completed = ?", array($problem));
46 $firstcourse = array_shift($courses);
47 $record = $DB->get_record('feedback_completed'.$suffix, array('id' => $problem));
49 $DB->update_record('feedback_completed'.$suffix, ['id' => $problem, 'courseid' => $firstcourse]);
50 foreach ($courses as $courseid) {
51 $record->courseid = $courseid;
52 $completedid = $DB->insert_record('feedback_completed'.$suffix, $record);
53 $DB->execute("UPDATE {feedback_value$suffix} SET completed = ? WHERE completed = ? AND course_id = ?",
54 array($completedid, $problem, $courseid));
58 // Part 2. Update courseid in the completed table.
59 $sql = "UPDATE {feedback_completed$suffix} "
60 . "SET courseid = (SELECT COALESCE(MIN(v.course_id), 0) "
61 . "FROM {feedback_value$suffix} v "
62 . "WHERE v.completed = {feedback_completed$suffix}.id)";