pt-online-schema-change的概述:alter a table's structure without blocking reads or writes.Specify the database and tablein the DSN.Do not use this tool before reading
its documentation and checking your backups carefully.
DSN:Data Source Name(資料庫源名稱)
工作原理是建立一個和你要執行alter操作的表一樣的空表結構,執行表結構修改,然後從原表
中copy原始資料到表結構修改後的表,當資料copy完成以後就會将原表移走,用新表代替原表,預設
動作是将原表drop掉。在copy資料的過程中,任何在原表的更新操作都會更新到新表,因為這個工具
在會在原表上建立觸發器,觸發器會将在原表上更新的内容更新到新表(轉自飛鴻大哥的)
關鍵參數介紹:
這裡有兩個參數需要介紹一下:
--dry-run 這個參數不建立觸發器,不拷貝資料,也不會替換原表。隻是建立和更改新表。
--execute 這個參數的作用和前面工作原理的介紹的一樣,會建立觸發器,來保證最新變更的資料會影響至新表。注意:如果不加這個參數,這個工具會在執行一些檢查後退出。這一舉措是為了讓使用這充分了解了這個工具的原理,同時閱讀了官方文檔。
執行個體:
use test;
set names gbk;
CREATE TABLE baike_student(
`userid` int(11) NOT NULL DEFAULT '0',
`username` varchar(12) NOT NULL DEFAULT '',
PRIMARY KEY (`userid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='百科學生表';
現在有加一個字段,code字段:
pt-online-schema-change --lock-wait-time=120 -uzsd -p'zsdzsd' -S /data/3307/mysql.sock --alter "add code smallint(6) NOT NULL DEFAULT '0'" D=test,t=baike_student --execute
從下面的日志中可以看出它的執行過程:
Altering `test`.`baike_student`...
Creating new table...
Created new table test._baike_student_new OK.
Altering new table...
Altered `test`.`_baike_student_new` OK.
Creating triggers...
Created triggers OK.
Copying approximately 1 rows...
Copied rows OK.
Swapping tables...
Swapped original and new tables OK.
Dropping old table...
Dropped old table `test`.`_baike_student_old` OK.
Dropping triggers...
Dropped triggers OK.
Successfully altered `test`.`baike_student`.
部分轉自飛鴻大哥的。
執行個體是自己做的。