diff --git a/course/lib.php b/course/lib.php index dc663aa38ea..dee093bbf48 100644 --- a/course/lib.php +++ b/course/lib.php @@ -1427,14 +1427,14 @@ function move_section_to($course, $section, $destination, $ignorenumsections = f // uniqueness constraint $transaction = $DB->start_delegated_transaction(); foreach ($movedsections as $id => $position) { - if ($sections[$id] !== $position) { + if ((int) $sections[$id] !== $position) { $DB->set_field('course_sections', 'section', -$position, ['id' => $id]); // Invalidate the section cache by given section id. course_modinfo::purge_course_section_cache_by_id($course->id, $id); } } foreach ($movedsections as $id => $position) { - if ($sections[$id] !== $position) { + if ((int) $sections[$id] !== $position) { $DB->set_field('course_sections', 'section', $position, ['id' => $id]); // Invalidate the section cache by given section id. course_modinfo::purge_course_section_cache_by_id($course->id, $id); diff --git a/course/tests/courselib_test.php b/course/tests/courselib_test.php index 391cac9ad4e..c75d8551880 100644 --- a/course/tests/courselib_test.php +++ b/course/tests/courselib_test.php @@ -1089,6 +1089,35 @@ class courselib_test extends advanced_testcase { $this->assertArrayNotHasKey(3, $sectioncaches); } + /** + * Test move_section_to method. + * Make sure that we only update the moving sections, not all the sections in the current course. + * + * @covers ::move_section_to + * @return void + */ + public function test_move_section_to(): void { + global $DB, $CFG; + $this->resetAfterTest(); + $this->setAdminUser(); + + // Generate the course and pre-requisite module. + $course = $this->getDataGenerator()->create_course(['format' => 'topics', 'numsections' => 3], ['createsections' => true]); + + ob_start(); + $DB->set_debug(true); + // Move section. + move_section_to($course, 2, 3); + $DB->set_debug(false); + $debuginfo = ob_get_contents(); + ob_end_clean(); + $sectionmovequerycount = substr_count($debuginfo, 'UPDATE ' . $CFG->phpunit_prefix . 'course_sections SET'); + // We are updating the course_section table in steps to avoid breaking database uniqueness constraint. + // So the queries will be doubled. See: course/lib.php:1423 + // Make sure that we only need 4 queries to update the position of section 2 and section 3. + $this->assertEquals(4, $sectionmovequerycount); + } + public function test_course_can_delete_section() { global $DB; $this->resetAfterTest(true);