6098 comments
2357 subscribers
6257 on Twitter
Subscribe! Feed reader E-mail

Drupal and Drush: Updating the database from the command-line

So now that we’re doing all our configuration changes in source code, it makes sense to automate database updates as much as I can. Here’s something I’ve added to drush_tools so that I can run all the schema changes from the command-line:

function drush_tools_update($command = '') {
  ob_start();
  require_once 'includes/install.inc';
  require_once 'update.php';
  $ret = ob_get_contents();
  drupal_load_updates();
  ob_end_clean();

  $list = module_list();
  $update_list = array();
  foreach ($list as $module) {
    $updates = drupal_get_schema_versions($module);
    if ($updates !== FALSE) {
      $latest = 0;
      $base = drupal_get_installed_schema_version($module);
      foreach ($updates as $update) {
        if ($update > $base) {
          if ($update > $latest) { $latest = $update; }
          $update_list[$module][] = $update;
        }
      }
      if ($latest) {
        sort($update_list[$module]);
        printf("%-30s %5d -> %5d (%s)\n", $module, $base, $latest, join(', ', $update_list[$module]));
      } else {
        printf("%-30s %5d\n", $module, $base);
      } 
    }      
  }
  if (count($update_list) == 0) return;
  if ($command != 'force' && !drush_confirm(t('Do you really want to continue?'))) {
    drush_die('Aborting.');
  }
  ob_start();
  foreach ($update_list as $module => $versions) {
    foreach ($versions as $v) {
      print "Running " . $module . "_update_" . $v . "\n";
      update_data($module, $v);
    }
  }
  $updates = ob_get_contents();

  cache_clear_all('*', 'cache', TRUE);
  cache_clear_all('*', 'cache_page', TRUE);
  cache_clear_all('*', 'cache_menu', TRUE);
  cache_clear_all('*', 'cache_filter', TRUE);
  drupal_clear_css_cache();
  ob_end_clean();
  $output = '';
  if (!empty($_SESSION['update_results'])) {
    $output .= "The following queries were executed:\n";
    foreach ($_SESSION['update_results'] as $module => $updates) {
      $output .= "\n" . $module . "\n--------------------------\n";
      foreach ($updates as $number => $queries) {
        $output .= 'Update #'. $number . ":\n";
        foreach ($queries as $query) {
          if ($query['success']) {
            $output .= "SUCCESS: " . $query['query'] . "\n";
          }
          else {
            $output .= "FAILURE: " . $query['query'] . "\n";
          }
        }
        if (!count($queries)) {
          $output .= "No queries\n";
        }
      }
    }
    $output .= "\n";
    print $output;
    unset($_SESSION['update_results']);
  }
}
Short URL: http://sachachua.com/blog/p/5154
  • http://www.eatsleepandcode.com Jason

    Thanks for this, I’ve wondered about how to do schema updates without having to switch to my browser, can’t wait to try it out!

  • Anonymouis

    This does not support multi-part updates.

  • http://growingventuresolutions.com greggles

    This is great news. Thanks for providing the code.

    There is an issue for this in the Drush issue queue http://drupal.org/node/194107

    Could you please post this as a patch to that? http://drupal.org/patch/create shows the style for Drupal patches.

    Thanks!

  • http://drupal.org/moshe Moshe Weitzman

    Cool – but it does not handle batch API style update. See http://cvs.drupal.org/viewvc.py/drupal/contributions/docs/developer/examples/batch_example.install?revision=1.3&view=markup for an example (look for ‘sandbox’). yched made same comment at http://drupal.org/node/233091#comment-992365

  • http://christian.roy.name/ Christian Roy

    This code that Sacha wrote is for Drupal 5 only.
    It is my understanding that the batch api was introduced in drupal 6.

    I posted Sacha’s patch into the drush project for drush-1.4-5.x

    http://drupal.org/node/194107#comment-1204613

    Since they are already working on a D6 and D7 version as a stand alone shell script, maybe this patch is not needed/wanted?

    • http://sachachua.com Sacha Chua

      Oh, that would be sweet! =D Even better way to do it.

  • Andreas Rydberg

    Hi Sacha.

    Thank you for you code. You seem to have inspired a lot of people with this, includeing me. I’ve used parts of you code to create a drush module for Drupal 6.x, which I’ve proposed to the drush-devs.

    Here is the link: http://drupal.org/node/366779

On This Day...

  • 2011: Learning new tricks about learning: maps and history — From Tuesday: J- has started Grade 8, the year before high school. Last schoolyear, we invested more time into helping [...]
  • 2010: ‘round the bend — You know those moments in formulaic movies. Our heroes hit their lowest points. Everything looks stressful. Then something changes, and [...]
  • 2009: Quick thoughts — I’m starting to accumulate a backlog of things to write about. Life is too interesting to capture, and yet too [...]
  • 2008: Drupal: Deploying two branches to three systems — To keep track of the bugfixes we’ll need to make for our next release, I’ve created a Subversion branch called [...]
  • 2008: Working on a small project — Working on a small project means that I wear multiple hats, and that’s helping me grow so much as a [...]
  • 2007: Weekly review — Here are the highlights of the last week: Finally got my paperwork together for the post-graduate work permit! After following up [...]
  • 2007: Attack of the killer tomatoes — Vine-ripened tomatoes were on sale at No Frills, so we bought some 15 pounds of plump, red, juicy, fragrant tomatoes. Mmm! [...]
  • 2006: Wow. Statistics can be fun. — I have a new favorite statistics textbook. Not that I had one before. Who knew that a statistics textbook could [...]
  • 2006: Self-portrait with vintage hat — One of the things that surprises people is that as high-tech and plugged in as I am, I still have an [...]
  • 2006: Twice-baked potatoes — One of the simple joys in life is waking up (relatively) early on a weekend morning and preparing a proper [...]
  • 2006: Networking party in New York that I really, really want to go to — The Greater IBM Initiative is having its first party in New York City on Thursday, Sept 21. I really, really [...]
  • 2005: Silk-screening workshop — Peach Berserk‘s silk-screening workshop looks amazing. I love their dresses, but not their prices! <laugh> Let’s start out by silkscreening something small, and [...]
  • 2005: Geekwear — I actually like wearing geek swag: clothes and accessories with a logo or geek reference. Geek swag identifies me to other [...]
  • 2005: Places to shop — ACT TWO 596 Mount Pleasant, 416-487-2486 Designer cast-offs CHOCKY’S 352 Queen West, 416-977-1831; 2584 Yonge, 416-483-8227 Pajamas and jackets ENDS 1930 Queen East, 416-699-2271, etc. Wool overcoats, etc. JO’S [...]
  • 2003: Linux in Education links — http://pchb1f.gallaudet.edu/tricki/
  • 2003: Plans for CS21A tomorrow — I think we’ll have fun. =) A lecture on searching and sorting - modified slides, whiz through most of it and [...]
  • 2003: CS1 site — - http://www.cs.up.ac.za/javagently/ListEx.html has a lot of examples, and it has an overarching project. Hmm. Stuff seems to come from the Java Gently [...]
  • 2003: Interesting words — - http://phrontistery.50megs.com/ - http://phrontistery.50megs.com/scrabble3.html
  • 2003: Hare Race — That didn’t go too well; not polished enough. The exercise is at HareRace-20030916.jar just in case.
  • 2002: (Mon Sep 16:23 2002, *Messages*) — Fixed planner remember bug – context was getting picked up after the switch of buffer.
  • 2002: (Mon Sep 16:59 2002, 2002.09.16) — Jean Paul Sartre self-making essentialism
  • 2002: (Mon Sep 16:34 2002, 2002.09.16) — http://www.jobstreet.com.ph/career/streetwise/women8.htm
  • 2002: (Mon Sep 16:52 2002, 2002.09.16) — http://www.xref-tech.com/

Get the highlights as a PDF!

Stories from my Twenties: Highlights from a Decade of Blogging

Free sample!