0

I'm just doing a one-off script, but I'm wondering if there's a correct "Drupal way" to alter a table and a unique key.

For example, this is essentially the query I want to do:

ALTER IGNORE TABLE `node_revision` ADD UNIQUE(`hash`);

And then if I later wanted to remove the unique index on hash, how would I also do that?

Does it have something to do with updating the database schema? or possibly db_change_field()?

2 Answers 2

2

db_add_unique_key() is the function you're looking for.

0

You can use hook_schema_alter and db_add_field in the hook_install of your module to modify exists tables.

This question is on on that exact subject.

6
  • I don't actually want to add the field, though, the field will already be added. I just want to add the fact that the column is unique.
    – Jack Ryan
    Feb 26, 2014 at 16:29
  • Oh, sorry. My bad. You were already on the right track with db_change_field.
    – Felix Eve
    Feb 26, 2014 at 16:33
  • I'm not quite seeing how I would add the unique modifier though. How would I do that with db_change_field()?
    – Jack Ryan
    Feb 26, 2014 at 16:47
  • Would it just be something like db_change_field('node_revision', 'hash', 'hash', array(), array('Unique' => array('hash')))
    – Jack Ryan
    Feb 26, 2014 at 16:49
  • See this page. "unique keys" is the array key you want to use. Also you need to pass in an associative array here.
    – Felix Eve
    Feb 26, 2014 at 16:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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