Drupal coder

Deleting Drupal variable directly in the database

This is just a quick caveat (or reminder). If you delete a variable from the variables table, always clear the cached entry of the variables too. Drupal caches the whole variables table in the cache table in an entry called 'variables'.

Here are two cases (of the many) you'll need this.

When you're writing your own module and you're setting some variables, always clean them up. Fastest way is by issuing a direct query to the database.

/**
 * Implementation of hook_uninstall().
 */
function my_module_uninstall() {
  db_query("DELETE FROM {variable} WHERE name LIKE 'my_module_%'");
  cache_clear_all('variables', 'cache');
}

A second typical case I can come up with is when releasing the cron semaphore after it got 'stuck'.

DELETE FROM variable WHERE name = 'cron_semaphore';
DELETE FROM cache WHERE cid = 'variables';
November 05, 2008Drupal, module development

Comments

Great post, I have been wondering about this for a while now, never got focused enough to figure it out until today. Thanks for the easy to find step by step tutorial.

Great post, I have been wondering about this for a while now, never got focused enough to figure it out until today. Thanks for the easy to find step by step tutorial.

Could you also use
drush vdel
?

useful post and comment, deleted the admin_theme variable after failed theme change and still had blank pages, clearing the variables cache resolved the problem.

thanks.

Be very careful when deleting your module's variables using "DELETE FROM {variable} WHERE name LIKE 'my_module_%'". You may accidentally delete another module's variables. For example your module is named 'blogger' and there exists another module named 'blogger_integration'. When that SQL is run, any blogger_integration module variables will be erased.

In my module's I've been leaning towards a new approach: I have a function called mymodule_variables():
<?php
function mymodule_variables() {
return array(
'mymodule_var1' => 'var1default',
'mymodule_var2' => 'var2default',
);
}
?>

Then I have a function that I use instead of variable_get:
<?php
function mymodule_var($name) {
static $defaults;
if (!isset($defaults)) {
$defaults = mymodule_variables();
}
$default = isset($defaults[$name]) ? $defaults[$name] : NULL;
return variable_get($name, $default);
}
?>

And now in the uninstall file, I can just loop through the array provided by mymodule_variables to automatically uninstall only mymodule's variables:
<?php
mymodule_uninstall() {
$variables = array_keys(mymodule_variables());
foreach ($variables as $variable) {
variable_del($variable);
}
}
?>

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

More information about formatting options