1、简介
pt-online-schema-change:在线修改表结构。
2、pt-osc的工作原理
1、创建一个和源表一样表结构的新表
2、在新表执行DDL语句
3、在源表创建三个触发器分别对应insert、update、delete操作
4、从源表拷贝数据到新表,拷贝过程中源表通过触发器把新的DML操作更新到新表中
5、rename源表到old表中,把新表rename为源表
6、删除源表
3、使用说明
语法:pt-online-schema-change [OPTIONS] DSN
pt-online-schema-change常用参数
pt-online-schema-change --help
常用参数:
--host=xxx:连接数据库的host--user=xxx:用户名--password=xxx:密码--ask-pass:手动输入密码--alter:结构变更语句,不需要 ALTER TABLE关键字。用逗号分隔可以指定多个更改D=db_name,t=table_name:指定要ddl的数据库名和表名--print:打印执行的SQL语句--dry-run:创建和更改新表,但不要创建触发器,复制数据和替换原始表。并不真正执行,可以看到生成的执行语句,了解执行步骤--execute:确定修改表,真正执行alter--alter-foreign-keys-method=s 设置修改外键的方式,一共有如下4个值: auto:优先选择rebuild_constraints方式处理外键,如果该方式不可用才选择drop_swap; rebuild_constraints:在最后rename表后,删除子表上的外键,并进行重新建立到新表的外键。 drop_swap:拷贝数据后,设置SET foreign_key_checks=0,直接将原表drop掉,然后rename临时表为新表 none:表示强制不考虑子表外键约束,设置SET foreign_key_checks=0,最终会导致子表外键约束到_table_old这个已删除的表上,不建议使用--preserve-triggers:保留触发器,当原表有触发器时需要指定该选项
4、示例
1 打印执行信息
pt-online-schema-change --host=192.168.136.129 --port=3306 --user=test --ask-pass --alter "add column name3 varchar(20)" D=test,t=test_osc --print --dry-run
2 新增字段
pt-online-schema-change --host=192.168.136.129 --port=3306 --user=test --ask-pass --alter "add column name3 varchar(20)" D=test,t=test_osc --print --execute
3 删除字段
pt-online-schema-change --host=192.168.136.129 --port=3306 --user=test --ask-pass --alter "drop column name3" D=test,t=test_osc --print --execute
4 修改字段
pt-online-schema-change --host=192.168.136.129 --port=3306 --user=test --ask-pass --alter "modify column name3 varchar(30)" D=test,t=test_osc --print --execute
5 索引操作
pt-online-schema-change --host=192.168.136.129 --port=3306 --user=test --ask-pass --alter "drop key ix_name2,add key ix_name3(name3)" D=test,t=test_osc --print --execute
6 主键操作
pt-online-schema-change --host=192.168.136.129 --port=3306 --user=test --ask-pass --alter "drop primary key,add primary key(name2)" D=test,t=test_osc --print --execute --no-check-alter