Austin Smith

Do it like Rails: Version your Drupal Database with hook_update

Fri, 07/17/2009 - 10:21

At The Economist, we've been struggling some to keep our database changes 100% in code. We're required to automate everything using hook_update and hook_install. We don't want to be pushing database imports around, and we want our build scripts to create a current database for testing purposes. Also, we want to see how the database is changing over time. How we do it? The answer might not surprise you--the Rake of Drupal is Drush.

The relative difficultly of this highlights an aspect of Drupal that's lacking in Rails: anyone can build a site without knowing PHP, and many devs (me included, on smaller projects) are perfectly happy clicking around the admin area, building views, creating blocks, and learning modules rather than writing code. Because there's no true site management area in Rails, if you want to make changes like these, you can either manipulate the database in SQL (and lose versioning) or write migrate scripts in Ruby. As a result, they have a much more robust and proven toolkit for these tasks--the drawback is that non-developers are shut out of application development.

Bit of background--Rake is a build tool for Ruby, which is used by Rails to execute schema changes by way of the command rake migrate. For each change, you write an "up" and "down" method. The up method progresses the system one version forward, the down one version back, so you have to write code that installs a feature and can also uninstall it. Our approach is a bit simpler due to API limitations for things like this; we just write upgrade functions.

The use of the install and update functions for contrib modules and your own functions will almost certainly differ. Contrib modules need an install function that will configure the module entirely on a clean system plus update functions that will move things around when you install a new version. Frankly, I'd like it if Drupal executed every update function on module installation and skipped hook_install altogether; the premise being that your lowest numbered update function (6001 for Drupal 6 modules) should install the lowest version of your schema. The only situation in which that would be inopportune is a module with hundreds of complex update functions that constantly back out of prior changes, and it'd only be really poor if it took so long that an unwitting site admin would cancel the module's installation using the browser's stop button because it took so long. Probably unlikely for most modules. We use our update functions like this; they're run progressively on installation. It saves us considerable development time versus building a purely clean install function.

The one potential pitfall to running update functions in this way is if the environment changes, a function might go missing or accept different parameters, which would cause our installation to break--this would be especially obnoxious on our Hudson Continuous Integration environment. So in this way we might find ourselves spending time refactoring old update functions, but this hasn't happened yet. This fact makes our approach much less tenable for contrib modules, which might depend throughout its update hooks on a certain environment configuration (e.g. one version of a function should exist in hook_update_6001 and another in hook_update_6010, but obviously only the most recent version actually exists). And contrib modules generally can't refactor their previous update functions either.

These problems aren't so severe in Rails because the migration system is generally simpler and on many applications would just involve creating database tables, for which there is seriously beautiful syntax--typical of Ruby. Managing your site's changes over time is critical to any framework--these tools aren't shipped with Drupal, like rake migrate is with Rails, but with a little bit of work, you can get very close!

Key Concepts in Automating Upgrades in Drupal

  • A current and widely discussed limitation of Drupal is its lack of API functions. There's sometimes no way around directly manipulating the database, but the Install Profile API is a great start.
  • Build your views and CCK types in the admin UI, then export them to code and install the exports using hook_update and the Install Profile API.
  • Download, install, and get to know Drush really well. Knowing and using Drush will make you efficient anyways.
  • Write build scripts in bash, make, or ant to install a ready-to-go version of your site with no database import required. This will make automating your unit tests much easier.
  • One bootstrap module with update functions that install other modules is effective. We use a Google spreadsheet to claim update numbers for our bootstrap module and have placed the URL to this document at the bottom of install file. You can and should install contrib modules this way too, but drupal_install_modules() will not fail if one or more dependencies listed in the install file are unmet, so be careful!
  • Get in the habit of writing your updates in code first, then running drush updatedb from the command line rather than making the changes in the admin area and then putting them in code to run later or on a CI server. The exceptions I make are for Views and CCK, which need to be exported to array structures.

Code snippets

Install function which iterates over hook_update functions

function ec_channel_install() {
  // Execute our defined updates.
  $version = 6001;
  while (function_exists('ec_channel_update_' . $version)) {
    call_user_func('ec_channel_update_' . $version++);
  }
  // hook_install has no return value
}

Create a content type

function ec_channel_update_6001() {
 
  install_include(array('node'));
 
  // Create the Channel Page content type.
  $props = array(
    'description' => t('Channel page, contains news packages, stories and blocks.'),
    'has_title' => TRUE,
    'title_label' => t('Channel Name'),
    'has_body' => FALSE,
  );
  install_create_content_type('channel', 'Channel Page', $props);
  return array();
}

Install Some Modules

function ec_channel_update_6003() {
  drupal_install_modules(array('content_multigroup', 'fieldgroup', 'link'));
  return array();
}

Import CCK fields

function ec_channel_update_6002() {
  $ret = array();
 
  // Economist Story node reference field.
  install_include(array('content', 'content_copy'));
  install_content_copy_import_from_file(drupal_get_path('module', 'ec_channel') .'/'.'freeform_story_link_econ_story.type', 'freeform_story_link');
  return $ret;
}

Related

You should check out the features module

Submitted by Adrian Rossouw (not verified) on Fri, 07/17/2009 - 12:36.

Features automates the capturing of your content types and views in code.

It's a lot less labor intensive than using install profile api AND it has great drush integration.

Very nice

Submitted by Austin Smith on Fri, 07/17/2009 - 13:43.

We started rolling before features was stable, but this is very cool. I will suggest it to my team!

I will suggest it to my

Submitted by Anonymous (not verified) on Sun, 02/06/2011 - 08:57.

I will suggest it to my team!
I agree!
Best Regards, Tadacip Posters team.

codes

Submitted by austin domeer (not verified) on Mon, 12/19/2011 - 10:35.

The codes are intelligently written. Pretty slick techniques you got there.
domeer @ mascara lotto results

Very cool article

Submitted by Bailey Garcia (not verified) on Mon, 12/19/2011 - 14:27.

This was really a very interesting and fun article for me to read. I really do appreciate all of this great and fun information. Single Parent Dating

Very helpful article

Submitted by Kate Reed (not verified) on Wed, 12/21/2011 - 16:04.

This was really so very interesting and fun for me to read. I really do think that this was great and awesome to read. I cant wait to read more from this very fun website. Koi Web

Very educational

Submitted by Cathy Carter (not verified) on Thu, 12/22/2011 - 10:31.

This was an excellent and helpful article to read. I have really enjoyed all of this great and fun information. This was a very special and fun information to me. Thanks - Conveyancing solicitors

I am pleased. I do not think

Submitted by drtey (not verified) on Mon, 12/26/2011 - 23:49.

I am pleased. I do not think Ive met anyone who knows as much about this topic as you do. You are truly well knowledgeable and very wise car insurance. You authored something that individuals could comprehend and created the topic fascinating for everyone.

Hi Austin, I would like to

Submitted by Levi Richards (not verified) on Sun, 01/08/2012 - 15:05.

Hi Austin, I would like to thank you again for another great share. I have been having difficulties implementing my code. Your share is much appreciated. Kudos to you. Paid Survey Reviews

You are very kind to drupal

Submitted by Donnie Steves (not verified) on Thu, 01/12/2012 - 10:10.

You are very kind to drupal newbies. Sharing is truly caring. These codes will come in handy on my next project. Thanks a lot. elliptical machines

That is really awesome and

Submitted by kllusers (not verified) on Thu, 12/29/2011 - 05:31.

That is really awesome and exciting to research your post! This is one of the best sites Ive ever research. You've got some mad capability here, man. I just confidence that you never decrease your style because you're definitely one of the best web entrepreneurs out there.online appointment scheduling service

A new drupal user here. I

Submitted by Alexander Moreson (not verified) on Mon, 01/02/2012 - 04:21.

A new drupal user here. I find your codes very helpful to newbies like me. Your work is very much appreciated. Texoma Guides

You saved me lots of time

Submitted by Laura Frits (not verified) on Sun, 01/15/2012 - 15:31.

You saved me lots of time with your share. I was about to give up on my codes. Your work is much appreciated. p90x workout schedule

This sort of write-up must

Submitted by zenler (not verified) on Wed, 12/28/2011 - 01:49.

This sort of write-up must read insanity for small site owners, but it's going on a lot at the corporate/enterprise level - much more than what we hear about in blogs. My suspicion is that people are frequently re-inventing the wheel, since you can't exactly commit an end-to-end process like this in a code repo. It's really great that you've taken the time to write this!
expensive cars

Thank you for the time you

Submitted by abelra8 (not verified) on Sat, 01/14/2012 - 11:21.

Thank you for the time you spent sharing your codes. Articles like this helps us newbies in drupal. Your work is much appreciated. offshore bank account uae

Good Post

Submitted by ianjark (not verified) on Mon, 01/09/2012 - 08:29.

Kindness is the language which the deaf can hear and the blind can see.If you can’t be content with what you have received, be thankful for what you have escaped.
Essay Writers

I just wished I could be as

Submitted by Steveson Wright (not verified) on Sun, 01/15/2012 - 15:34.

I just wished I could be as proficient as a programmer like you. I guess I have to study more to reach your programming level. exercise at home

Awesome demonstration on this

Submitted by zeondi (not verified) on Mon, 01/09/2012 - 20:57.

Awesome demonstration on this publish. From this publish I acquired several of new elements and details for which I can say that probably will be useful for upcoming . Thanks for discussing excellent content and exciting facts!
Hemorrhoid Treatment

This is one of the most

Submitted by markine (not verified) on Fri, 12/30/2011 - 19:05.

This is one of the most beautiful blog I've read a lot of time. The amount of information here is fantastic, almost like he wrote a book about it. Your blog is great for anyone who wants to understand more about this subject.remortgage-search.com

The illustrative idea is

Submitted by mardeu (not verified) on Thu, 01/05/2012 - 06:22.

The illustrative idea is relaxing awesome. We can quickly view the different selections. I am admiring your effort about this topic and asking you to cause more such cost-effective techniques.
wordpress plugins

Re: KHL Medveščak Postao/la

Submitted by doFqwer (not verified) on Wed, 08/31/2011 - 12:58.

Re: KHL Medveščak
Postao/la Lesi78 » 31 kol 2011 15:12

Po mom misljenju Heko si je sam kriv. Previse se uzivil u janjetinu i rakiju. Pa onda je jos dobil i prinovu, koja ga je najvjerojatnije omela u ucestalom odlasku u teretanu. Kazu da je skinul 9 kila prek ljeta, ali je glavno pitanje da li vjezbanjem ili mijenjanjem pelena. Nisu mu bas neke sanse da prodje probu u . Osim ak im ne treba netko tko ce samo stajat i tu tamo kojega zabit. Mozda bi mogel u za Slohokej ligu.

A za mighty Joela smo svi culi jos prosle godine da ga se ne da sedlat i da mu disciplina nije jaca strana. Mozda ga Marty-u ne misli trpit cijelu sezonu. A i ova ozljeda ga mozda ostavi u rosteru, jer ga sad vise nemaju kom uvalit.

El capitano ostaje sigurno. Kod njega je problem samo da li jos uvijek moze izdrzat ritam EBEL-a ili ce igrat svaku trecu.

I am glad that I have come

Submitted by lisman (not verified) on Thu, 12/29/2011 - 01:48.

I am glad that I have come across your site. However my expertise in this field is just comparable to a novice. I am very grateful to have come here as I know I would learn a lot from you.free credit report

Küstenpatent,

Submitted by Küstenpatent, (not verified) on Sat, 01/21/2012 - 05:26.

Even if this does work out, the presence or lack thereof of the session cookie shouldn't be a deciding factor in whether to send an expires header in the future or not--I can absolutely imagine wanting both; again, a store at /store and content at / would necessitate this.

Shame Features doesn't work.

Submitted by Anonymous (not verified) on Thu, 12/30/2010 - 14:09.

Shame Features doesn't work. Oh sure you can export your CCK, but try importing it. You see it in CCK, you see it in Features, but you DON'T get the capability to create content types with the content type you imported. Giant Fail.

This is a nice post in an

Submitted by Anonymous (not verified) on Tue, 12/06/2011 - 13:26.

This is a nice post in an interesting line of content, great way of bring Do it like Rails: Version your Drupal Database with hook_update to discussion.
Thanks for sharing this article, keep up the excellent work !
arginina

Great

Submitted by michaeljii (not verified) on Mon, 07/25/2011 - 05:54.

The particulars and exact recommendation are insurance specifically what I was wanting. I’ve book marked and will definitely be returning.business insurance Thanks for the information in this blog.The posting in this site is very cool and also car insurance interesting.I had read the entire blog and I came to know many things which dental insurance I don't know before.I am sure that the visitors who visit this site will also be enjoying reading the posts.Keep it up.Waiting for new posts from you to be posted in this site.
JN0-343\1z0-050\312-49\70-270\650-299\000-152\350-040\642-185\642-467\646-223
Regards,
MichaeL || NYC.USA.

SuperB!

Submitted by arranbruno (not verified) on Wed, 01/11/2012 - 05:15.

Its meaningful and by some means sharing this to readers like me, can make me want to surf the web to be able to get extra fantastic ideas.Write My Essay

Nice One!

Submitted by marshalreon (not verified) on Wed, 01/11/2012 - 05:19.

My friend mentioned it before, but never got around to it looking so far. I must express, knocked me down
Essay Help

Great Post!

Submitted by davidtimberwilson (not verified) on Wed, 01/11/2012 - 05:29.

Good read. There is currently quite a lot of information around this subject on the net and some are most definitely better than others. You have caught the detail here just right which makes for a refreshing change.Logo Design Contest

Make sure you shine at your

Submitted by parquet flooring (not verified) on Mon, 01/16/2012 - 22:29.

Make sure you shine at your next party, choose exquisite parquet flooring from fabulous collections by big designers.

Küstenpatent,

Submitted by Küstenpatent, (not verified) on Sat, 01/21/2012 - 05:25.

Even if this does work out, the presence or lack thereof of the session cookie shouldn't be a deciding factor in whether to send an expires header in the future or not--I can absolutely imagine wanting both; again, a store at /store and content at / would necessitate this.

PJKhEzUXeSrGXuwR

Submitted by Qnwtfffh (not verified) on Fri, 11/12/2010 - 21:12.

Prometheus's failure confers upon the separation of mortals and immortals the character of a fall. , ahvd.com, [url="http://qhdwuz.weherod.co.cc/ahvd.com.html"]ahvd.com[/url], http://qhdwuz.weherod.co.cc/ahvd.com.html ahvd.com, 5485,

The key concepts of

Submitted by Dicksons (not verified) on Sun, 01/02/2011 - 09:03.

The key concepts of automating upgrades in Drupal are really helpful for me. It cleared much of my confusion about the subject and in all procedure of its use. I was finding out the answers to my problems related to Drupal updates from many days and came across this site while surfing on net. I got a ready information without any efforts and really glad for that. I will suggest it to my colleagues and will discuss it in detail with them. I really appreciate the hard work behind such updates.
http://www.debtsoftware.com/

Rails is the best thing that

Submitted by james lee (not verified) on Tue, 01/04/2011 - 14:35.

Rails is the best thing that you can use. I use it at work all the time and just love it. It definitely makes my job easier at work. The process is so good. whistleblower policy

This blog is very nice.I

Submitted by Jason Miller (not verified) on Fri, 01/21/2011 - 13:33.

This blog is very nice.I really like such a fantastic written blog.I will keep coming here again and again.Visit my link as well. seo link service

Great post

Submitted by yana (not verified) on Tue, 10/18/2011 - 07:38.

You helped me a lot indeed and reading this your article I have found many new and useful information about this subject. Thanks for sharing this!
Banquetes

This is the web page for all

Submitted by freone (not verified) on Fri, 12/23/2011 - 06:00.

This is the web page for all those who want to know about this topic. It definitely put a new whirl on a topic that has been published for many.Gift Holders have discovered your web page website while looking for such details in different.
wool rugs

I am impressed by the quality

Submitted by Anonymous (not verified) on Tue, 02/08/2011 - 06:17.

I am impressed by the quality of information on this website. There are a lot of good resources here. I am sure I will visit this place again soon. PLR articles

This is a great blog with

Submitted by nabiha (not verified) on Thu, 03/10/2011 - 04:00.

This is a great blog with excellent posts and links.
Thanks for sharing.Flower Shop in UK|flowers of germany

Makes Sense

Submitted by actron cp9180 (not verified) on Thu, 03/17/2011 - 06:39.

This post makes a lot of sense. Thanks for sharing!
obd ii scanner reviewsEquus 3160Equus 3140Actron cp9175Actron cp9580

I prefer Joomla for cms but

Submitted by John (not verified) on Fri, 03/25/2011 - 07:29.

I prefer Joomla for cms but drupal is good too.Drupal can be a bit slow at times and buggy too but the latest updates have fixed it.This is John from juicer reviews

ace

Submitted by Customize Shirts (not verified) on Tue, 04/12/2011 - 07:35.

Thanks for pointing that out! I guess I got carried away with the simplicity. The post has been updated.

I can see that you are make

Submitted by motorola xoom price (not verified) on Thu, 05/05/2011 - 18:06.

I can see that you are make great efforts into your blog. Keep posting great article like this. I will come back again to your site. You can choose asus ep121to surf and read other article from this blog.

Cool

Submitted by CitesteAsta (not verified) on Tue, 05/24/2011 - 18:33.

Super sexy coding there me8 :)) really enjoyed it

excellent

Submitted by mac running slow (not verified) on Fri, 06/03/2011 - 14:38.

great coding, really really helped! I have been trying to figure out this code for agaes, so thank you very much!

re:

Submitted by thetoxicguy (not verified) on Thu, 07/07/2011 - 04:34.

there is no doubt that we are now in a world where we come across different and strange things happening in this world. Innovation is everywhere, personally I am also a fan of innovation, no matter in studies, technologies, science, beauty, fashion (but it should be good for human kind an world). there are alot of courses like ccnp dumps | ccnp security dumps | ccnp wireless dumps \ ccsp dumps | cisco dumps | cissp dumps | citrix dumps | comptia dumps | crm dumps | cwna dumps | db2 dumps | itil v3 dumps . In recent past it was just ok to get a master degree in any of the running field and set your career we are much more into virtual studies and doing all those stuffs where we can explore and learn more.. a lot certifications introduced by Microsoft, Cisco and other international certifications in which you can study and get a good career too. I am so happy to be part of this revolutionary field and do suggest you too. because at the end "it always up to you to decide"...thanks!!

I am not really surprised to

Submitted by thespecialist (not verified) on Sun, 07/10/2011 - 13:36.

I am not really surprised to see that I read just a new thing which I never knew before, I like the way its been expressed, some of the reservatiosn are there but it always happen coz nothing goes perfect and you can see it anywhere even my ...... can also give you the example that how good I care about fantastic things.
ed hardy sunglasses

Le chantier de la

Submitted by tabe' di' (not verified) on Sun, 07/24/2011 - 20:03.

Le chantier de la construction du château de Versailles (ainsi que des jardins et des systèmes hydrauliques) n'a pas été assez étudié du point de vue de l'histoire de l'administration. Il constitue pourtant, de toute évidence, le symbole de la capacité de l'administration royale d'assurer la maîtrise d'ouvrage du plus important édifice civil européen, d'être un concours efficace à la concrétisation de l'absolutisme et de produire un chef d'œuvre destiné à la longue durée. acer iconia

The 55-inch Vizio XVT3D554SV

Submitted by VIZIO XVT3D554SV (not verified) on Wed, 07/27/2011 - 22:46.

The 55-inch Vizio XVT3D554SV sports a 480Hz refresh rate, 4 millisecon response and support for a suite of web apps on top of 3D

From the perspective of a

Submitted by johnmartin (not verified) on Fri, 07/29/2011 - 04:33.

From the perspective of a test developer, there is great variability with respect to time and effort needed to prepare a test. Likewise, from the perspective of a test taker, there is also great variability with respect to the time and needed to obtain a desired grade or score on any given test.
cisco braindumps
cissp braindumps
citrix braindumps
comptia braindumps
crm braindumps
cwna braindumps
db2 braindumps
itil v3 braindumps

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> <img> <p>
  • Lines and paragraphs break automatically.

More information about formatting options