作者:老葛,北京亚艾元软件有限责任公司,http://www.yaiyuan.com
我们在前面定义了block_morelink这个数据库表。但是有人在使用的过程中,出现错误,并且在我们的项目页面提交了bug,http://drupal.org/node/1159446,“Install Exception on new site: Syntax error or access violation: 1071 Specified key was too long”。这个问题的原因是,url,title的长度加在一起超过了主键的限制。此时我们需要修改数据库模式的定义。
将block_morelink_schema中的主键
'primary key' => array('module', 'delta', 'url', 'title'),
修改为:
'primary key' => array('module', 'delta'),
对于那些已经安装了这个模块的用户来说,我们需要为其提供一个升级路径,代码如下:
/**
* change 'primary key' to array('module', 'delta').
*/
function block_morelink_update_7000(&$sandbox) {
db_drop_primary_key('block_morelink');
db_add_primary_key('block_morelink', array('module', 'delta'));
}
在这里我们实现了钩子函数hook_update_N(&$sandbox),由于这是block_morelink模块的第一个更新函数,所以我们将这里的N设置为了7000,那么第二个更新函数就应该是7001了。在钩子函数中,我们首先删除了原有的主键,接着添加了新版的主键。Drupal会追踪模块模式的当前版本,在运行完这个更新以后,该模块的模式版本就设置为了7000,这一信息存储在system表的schema_version列中。
我们再看一个例子,这段代码摘自于feeds模块的install文件:
function feeds_update_7100(&$sandbox) {
$spec = array(
'type' => 'text',
'size' => 'big',
'not null' => FALSE,
'description' => 'State of import or clearing batches.',
'serialize' => TRUE,
);
db_change_field('feeds_source', 'batch', 'state', $spec);
$spec = array(
'type' => 'text',
'size' => 'big',
'not null' => FALSE,
'description' => 'Cache for fetcher result.',
'serialize' => TRUE,
);
db_add_field('feeds_source', 'fetcher_result', $spec);
}
在这个更新中,首先是将feeds_source中的字段batch重命名为了state,接着添加了一个新的字段fetcher_result。注意这里面分别用到了db_change_field和db_add_field。