0

I'm attempting to insert a row into a table created by another module. This module was enabled in a previous hook_update_N(); I want to insert a row into the table with another hook_update_N() or the same one. Using two hook_update_N() works when the updates are ran at different times but if both updates are ran at once the second update fails because the table does not yet exist. I have tried using sleep() but that seems problematic.

/**
 * Enable commerce fees
 */
function mymodule_update_7004($node) {
  module_enable(array('commerce_fees'));
}

/**
 * create compliance fee
 */
function mymodule_update_7005($node) {
  // wait for commerce_fee table to be created
  sleep(10);
  if (db_table_exists('commerce_fees') == TRUE) {
      db_insert('commerce_fees')
    ->fields(array(
      'name' => 'non_compliance_fee',
      'title' => 'Non-compliance Fee',
      'display_title' => 'Refundable Non-compliance Fee',
      'description' => '',
    ))
    ->execute();

    // Clear the necessary caches and rebuild the menu items.
    commerce_fees_reset();
    entity_defaults_rebuild();
    menu_rebuild();
  }

  else {
    drupal_set_message('table commerce_fees does not exist');
  }
}
2

I recommend using DrupalUpdateException to make update 7005 fail if the table doesn't exist so that it can be ran again when the table has been added, or at least notify the web builder that the table doesn't exist and needs to be worked on.

2
  • Thanks @DamienMckenna this does address the failure but doesn't fix the problem. – kepford Aug 31 '13 at 23:54
  • And now I see the typo in my previous hook_update_N(). – kepford Sep 1 '13 at 2:12
1

Here is the working code after adding DrupalUpdateException.

/**
 * Enable commerce fees
 */
function my_module_update_7004($node) {
  module_enable(array('commerce_fees'));
}

/**
 * create compliance fee
 */
function my_module_update_7005($node) {

  if (!module_enable(array('commerce_fees'))) {
    throw new DrupalUpdateException('This version of My Module requires commerce fees module, but it could not be enabled.');
  }
  if (db_table_exists('commerce_fees') == TRUE) {
      db_insert('commerce_fees')
    ->fields(array(
      'name' => 'non_compliance_fee',
      'title' => 'Non-compliance Fee',
      'display_title' => 'Refundable Non-compliance Fee',
      'description' => '',
    ))
    ->execute();

    // Clear the necessary caches and rebuild the menu items.
    commerce_fees_reset();
    entity_defaults_rebuild();
    menu_rebuild();
  }

  else {
    DrupalUpdateException('The table commerce_fees does not exist');
  }
}
0

You can use hook_update_dependencies to ensure the correct update sequence.

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.