I'm doing a bit of bug fixing on a module, and one bug revolves around an outdated method of deleting files on uninstall. The uninstall shouldn't be doing an unmanaged mass delete of an entire upload directory anyway, now that files are managed in the database.

My question is this: do I need to explicitly remove file usage by this module in hook_uninstall, or does Drupal take care of this?

If the answer is that I do need to remove all the file usage (via something like file_usage_delete, file_delete), I could use some pointers on how to determine what files are in use by the module.

Comments

jaypan’s picture

I doubt files are automatically removed when a module is uninstalled, but you'd have to check to determine that for sure. I would imagine they are not, because it may delete files without the user expecting that.

You could determine if a file is ready to be deleted by querying the {file_usage} table, for all files with a 'type' of your module name, and a 'count' of 1 (meaning that the file is only being used one time, and by your module).

Contact me to contract me for D7 -> D10/11 migrations.

indyana’s picture

I did a few tests, and the file usage isn't automatically canceled on uninstall or the next cron after, which means all the managed files stick around, even if my module was the only one using them. Thanks for pointing me in the right direction. I'll post my final solution here once I've got it working and then mark this solved.

jaypan’s picture

I did a few tests, and the file usage isn't automatically canceled on uninstall or the next cron after

By the way, it won't necessarily be the next cron run after. It's the next cron run after 6 hours after the file is deleted. So if the file is deleted through Drupal at 12:00, the actual file in will be deleted from the file system on the next cron run after 6:00.

Contact me to contract me for D7 -> D10/11 migrations.

indyana’s picture

Good to know! I'm still a bit hazy on Drupal 7 file management... thanks for all the feedback.

indyana’s picture

Expanded the suggestion above to remove all possible file usage by the module and then see if files can be deleted. Following code added to the modules hook_uninstall function:

// Check for files in use by my_module_name
$result = db_query("SELECT fid FROM {file_usage} WHERE module = 'my_module_name'");

foreach ($result as $record) {
  $file = file_load($record->fid);
  if ($file) {
    // Remove all usage for this file by my_module_name
    file_usage_delete($file, 'my_module_name', NULL, NULL, 0);
    // Should only delete if file not in use by another module
    file_delete($file);
  }
}
jaypan’s picture

Nice solution. This way the module cleans up after itself.

Contact me to contract me for D7 -> D10/11 migrations.