David Lohmeyer's Blog

Clean up database pollution from the migrate Drupal module

I'm working on a large, complex migration from Drupal 7 to Drupal 8 right now. One thing I noticed is that the migrate modules pollute the database with an unreal number of tables which allow migrations to be re-run, etc. Well if you don't need that, here's how to remove these tables. Currently the migrate modules don't clean up after themselves. Put this in a custom module or PHP script that has bootstrapped Drupal. Note this code only works in Drupal 8. Shown is a .install file for a custom module. If you uninstall the custom module, it will run the cleanup:

/**
 * Implements hook_uninstall().
 *
 * Removes stale migration configs during uninstall.
 */
function MY_MODULE_uninstall() {

  // Clean up database pollution
  $tables_to_cleanup = [
    'migrate_message_',
    'migrate_map_',
  ];

  $query = db_query('show tables;');
  $schema = $query->fetchAll();
  
  foreach ($schema as $table_name) {
    $table_name = (Array) $table_name;
    $table_name = reset($table_name);
    foreach($tables_to_cleanup as $table_to_cleanup) {
      if(strpos($table_name, $table_to_cleanup) !== false) {
        db_drop_table($table_name);
      }
    }
  }

  // Clean up old migrate configuration
  $query = db_select('config', 'c')
    ->fields('c', array('name'))
    ->condition('name', db_like('migrate_plus.') . '%', 'LIKE')
    ->execute();

  $config_names = $query->fetchAll();

  // Delete each config using configFactory.
  foreach ($config_names as $config_name) {
    \Drupal::configFactory()->getEditable($config_name->name)->delete();
  }
}

 

Related Posts