您的位置:首页 > 其它

pt-online-schema-change 存在 trigger的表无法改动 hack

2018-01-21 19:44 597 查看
pt-online-schema-change,一个用来修改线上数据库表的工具,可以在不影响业务(锁表)的情况下,修改数据表。

不过表里有索引,那么pt-online-schema-change会报错:

The table ‘your table’ has triggers. This tool needs to create its own triggers, so the table cannot already have triggers

为什么表里有trigger就不能用pt-online-schema-change这个工具了呢?

这要从pt-online-schema-change的工作机制说起。

pt-online-schema-change的原理:

1. 根据给定的修改条件,新建一张空表。这里就叫新表吧。

2. 给需要修改的表(这里叫旧表吧)添加三个trigger,三个trigger将对旧表对增删改同时写入新表。

3. copy 旧表数据到新表。

4. 旧表数据全部写入新表后,新表名称改为旧表名称。

5. 删除trigger,删除旧表。

由于pt-online-schema-change本身的工作机制用到了trigger,pt-online-schema-change在执行过程中首先检查表的trigger情况:

show triggers like “you_table”

所以在表有已经有trigger的情况下,不能使用pt-online-schema-change。

不过,还有一线生机,如果表里只有
before
类型的trigger,那么,可以通过修改pt-online-schema-change中的两行源码来绕过对表上trigger检查。

1 首先检查需要改动的表没有
after trigger
类型对触发器。

2 将pt-online-schema-change源码一下三行:

# There cannot be any triggers on the original table.
my $sql = 'SHOW TRIGGERS FROM ' . $q->quote($orig_tbl->{db})
. ' LIKE ' . $q->literal_like($orig_tbl->{tbl});


改成:

# There cannot be any AFTER triggers on the original table.
my $sql = "SHOW TRIGGERS FROM " . $q->quote($orig_tbl->{db})
. " WHERE `Table` = '$orig_tbl->{tbl}' AND `Timing` = 'AFTER'";


update

gh-ost工具是一个比pt-online-schema-change更灵活的在线修改mysql schema的工具。

gh-ost的安装与使用参考这里
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: