7

I'm looking to add a column called 'updated' directly to the users table.

The Field API and Joins are not an option for me in this case due to external constraints.

How can I safely modify the user_schema to add the 'updated' column in a custom module and safely clean it up when the module is removed?

Here is the layout of the 'updated' column based on the Schema API:

  $field = array(
      'type' => 'int',
      'not null' => TRUE,
      'default' => 0,
      'description' => 'Timestamp for last time user was updated.',
  );

Currently my attempts using hook_install are not working as I believe they should.

5

It seems that I was missing hook_schema_alter(). This fixed my issues with drupal_write_record() and views. Thank you @Clive for your comment here.

Overview of what you need to do:

Actual Code:

Here is how I accomplished this. The code below belongs in your module.install file.

function hook_install() {
  $field = array(
      'type' => 'int',
      'not null' => TRUE,
      'default' => 0,
      'description' => 'Timestamp for last time user was updated.',
  );
  $index = array(
      'indexes' => array(
          'updated' => array('updated')
      ),
  );
  db_add_field('users', 'updated', $field, $index);
}
function hook_schema_alter(&$schema) {
  $schema['users']['fields']['updated'] = array(
      'type' => 'int',
      'not null' => TRUE,
      'default' => 0,
      'description' => 'Timestamp for last time user was updated.',
  );
}

function hook_uninstall() {
  db_drop_field('users', 'updated');
}
  • I created an empty mymodule.module. And added a mymodule.info (for it to be visible in the module list), and mymodule.install (using the above code). Changed all "hook_" with "mymodule_". In order to uninstall changes, you have to deselect the module, go to the uninstall tab, and check that. Uninstalling that way removes all data associated with that field. – sksallaj Sep 10 '16 at 5:13
  • I could be mistaken, but generally when uninstalling a module, you're looking to remove all traces the module having being created/added. – Citricguy Sep 10 '16 at 12:36
  • Yes, but when I was trying to update a field, you have to uninstall it, and reinstall it again to apply the update. Drupal simply won't update the code when there's changes to the column in the code above. That's why certain procedures has to be taken into consideration before the update. – sksallaj Sep 16 '16 at 2:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.