Using .install to update your database

You can use your .install file with update.php to alter your database.

If you are writing a module or updating an old one and your new version requires changes to your database, this can be achieved by adding code to your .install file.

Open your .install file and add a new blank update. Be advised the number will be the next available number.  We would recommend putting a buffer of a couple of number in. This makes your job easier when you have to do a lot of debugging.

function freepizza_update_100() {

}

In this example, freepizza is the machine name of your module.

This is a blank update that will be execute when update.php is run or updb is run via drush.

If you want to create your table you will have to add a schema array.  The schema array contains the field names and types of your schema.

How do you get the schema array?  You can manually create it, but there is a better way.  We recommend using the schema module.  It can create the array perfectly.  Just copy and paste it.

function freepizza_update_100() {
  $schema['pizzatable'] = array(
    'description' => 'Table about pizza',
    'fields' => array(
      'extra_toppings' => array(
        'description' => '',
        'type' => 'text',
        'not null' => FALSE,
      ),
      'size_inches' => array(
        'description' => '',
        'type' => 'int',
        'not null' => FALSE,
      ),
    ),
  );
  
  db_create_table('pizza', $schema['pizzatable']);
}

This schema will create a table named pizztable with two fields: extra_toppings and size_inches.

The db_create_table statement handles all the back end work of creating the table.  This function takes the outlines schema pizztable and creates the table pizza in your database.

With the new .install code in your site, its almost time to update the site.  Before you update, back up everything!  If you made a slight mistake in your code, your site could become unresponsive, thus dead.

If you are happy, run the update.php or drush updb command.  When you look at your database, you will see your new table!