By default, drush updb clears the cache after applying database updates. For deployments where you want to avoid an unnecessary performance hit, you can prevent this default behavior using a Drush pre-command hook. The updb command has a --cache-clear flag that you can set up in your CI workflow, but what about local testing? Will you or your team remember to set that flag every time?
I've come to learn this may be a controversial take. This requires having a deployment identifier set and crafted update hooks for specific cache invalidations, router rebuilds, etc. But if you want a highly performant Drupal application with faster deployment times, it's crucial.
The hook
You can register a Drush hook to override the default --cache-clear option on the updb command. This effectively automates using the --no-cache-clear flag.
<?php
declare(strict_types=1);
namespace Drupal\my_module\Drush;
use Drush\Commands\DrushCommands;
use Consolidation\AnnotatedCommand\CommandData;
use Consolidation\AnnotatedCommand\Hooks\HookManager;
use Drush\Attributes as CLI;
use Drush\Commands\core\UpdateDBCommands;
final class MyModuleDrushCommands extends DrushCommands {
/**
* Disable the cache clear option for the updb command.
*/
#[CLI\Hook(type: HookManager::PRE_COMMAND_HOOK, target: UpdateDBCommands::UPDATEDB)]
public function disableUpdbCacheClear(CommandData $commandData): void {
$commandData->input()->setOption('cache-clear', FALSE);
}
}How It Works
#[CLI\Hook(...)]: This attribute registers the method as a Drush hook.type: HookManager::PRE_COMMAND_HOOK: The hook executes before the mainupdbcommand.target: UpdateDBCommands::UPDATEDB: This limits the hook's execution to only theupdbcommand.$commandData->input()->setOption('cache-clear', FALSE): This line programmatically sets the--cache-clearoption toFALSE, overriding the defaultTRUEvalue.
For Drush to discover this command class, it must be located in a namespace registered with Drush's auto-discovery mechanism. A typical pattern is to place this code in a custom module's src/Drush/Commands directory or in a global command class that lives outside of a module.
Photo by Mahdi Bafande: https://www.pexels.com/photo/irregular-streaks-of-lights-15629018/
Want more? Sign up for my weekly newsletter