Is there an optimal method to grant permissions for a newly added permission defined by hook_permission? I'm attempting to deploy a new permission and granting in a single update.

I have custom.module which defines a new permission with hook_permission:

function custom_booking_permission() {
  return array(
    'custom allow registration' =&gt; array(
      'title' =&gt; t('Fill out Registration Form'),
      'description' =&gt; t('Allows a user to register their online account.'),
    ),
  );
}


And then in the custom.install in hook_update_n:

function custom_booking_update_7002() {
  user_role_grant_permissions(DRUPAL_ANONYMOUS_RID, array('custom allow registration'));
}


The problem is that when I deploy this code and run drush updb -y in my script, I get this error:


  SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'module' cannot be null                                       [error]


Which as I understand it is because Drupal has yet to recognise the new permission in hook_permission.

I have other aspects to the update script such as enabling modules and reverting features, and then running drush updb later in the script works fine. However I've always believed that drush updb should be as early as possible. Maybe I just need to be more flexible.

Alternatively I was thinking about either an SQL insert to avoid the grant permission validation, or running a drush php-eval later in the deployment script separate from drush updb. Both strike me as undesirable.
The only reason Drupal would not know of the new permission is because it hasn't yet registered your hook. This would only happens after a cache clear.

I would not advise to run a full cache clear before an update (as that might well invoke code that will expect the update to have been run already). Maybe you could get away with clearing the cache of hooks in module_implements. You could call this in your hook_update_N before setting the role:

module_implements('permission', FALSE, TRUE);


But even that feels a bit risky ; it is best not to interfere with the way things run, you might end up with debugging headaches.

Otherwise I don't think there is a perfect solution. Drupal just doesn't have a 'post-update' style hook. You could implement such a hook yourself (maybe using a variable_get/set and hook_init ; or as a drush script as you suggest), however this feels like a complicated way to do what could otherwise be done with a simple SQL query.

If you know your target uses an SQL database, then I think that, while not entirely satisfying, the SQL insert statement is the simplest solution.