/** * Reset all database tables to default values. * @static * @return bool true if reset done, false if skipped */ public static function reset_database() { global $DB; if (!is_null(self::$lastdbwrites) and self::$lastdbwrites == $DB->perf_get_writes()) { return false; } $tables = $DB->get_tables(false); if (!$tables or empty($tables['config'])) { // not installed yet return false; } if (!$data = self::get_tabledata()) { // not initialised yet return false; } if (!$structure = self::get_tablestructure()) { // not initialised yet return false; } $empties = self::guess_unmodified_empty_tables(); foreach ($data as $table => $records) { if (empty($records)) { if (isset($empties[$table])) { // table was not modified and is empty } else { $DB->delete_records($table, array()); } continue; } if (isset($structure[$table]['id']) and $structure[$table]['id']->auto_increment) { $currentrecords = $DB->get_records($table, array(), 'id ASC'); $changed = false; foreach ($records as $id => $record) { if (!isset($currentrecords[$id])) { $changed = true; break; } if ((array)$record != (array)$currentrecords[$id]) { $changed = true; break; } unset($currentrecords[$id]); } if (!$changed) { if ($currentrecords) { $lastrecord = end($records); $DB->delete_records_select($table, "id > ?", array($lastrecord->id)); continue; } else { continue; } } } $DB->delete_records($table, array()); foreach ($records as $record) { $DB->import_record($table, $record, false, true); } } // reset all next record ids - aka sequences self::reset_all_database_sequences($empties); // remove extra tables foreach ($tables as $table) { if (!isset($data[$table])) { $DB->get_manager()->drop_table(new xmldb_table($table)); } } self::$lastdbwrites = $DB->perf_get_writes(); return true; }