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';
Written on November 05, 2008 at 07:49, tagged as caveats, Drupal, module development

Comments

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

About

drupalcoder.com is a blog on all things Drupal in specific and LAMP on OS X in general. It is maintained by Davy Van Den Bremt, a Belgian (Drupal) web developer and designer living in Ghent. The goal of this blog is to log all interesting things that have crossed the writer's path while developing Drupal sites. You can read all about Davy's professional activities on his LinkedIn profile. If you want to get in touch, use the contact form.