常見線上變動表結構的方法有兩種,第一種是online ddl ,alter, 第二種是用相似工具percona。本文主要用實例描述下第二種方式的基本原理。app
percona 等工具的原理比較簡單。1,copy 一個新表;2,alter 表結構; 3,添加 update, delete, insert 三個觸發器;4,insert igonore 原表的數據;5,刪掉觸發器。這裏不用加鎖就是由於有觸發器在同步新增的改動,全部,一旦之前表有觸發器,就不適合這種方式。工具
1, 新建一個表日誌
create table person(id int ,name varchar(8), PRIMARY KEY (id)) ;
2, 插入1條記錄code
insert person (id, name) values (1, "zhangsan");
3, 變動表結構ci
pt-online-schema-change --alter 'add column sex varchar(100)' p='123456',u=root,D=test,t=person --no-check-replication-filters --execute
4, 日誌解析:同步
No slaves found. See --recursion-method if host didi has slaves. Not checking slave lag because no slaves were found and --check-slave-lag was not specified. Operation, tries, wait: analyze_table, 10, 1 copy_rows, 10, 0.25 create_triggers, 10, 1 drop_triggers, 10, 1 swap_tables, 10, 1 update_foreign_keys, 10, 1 Altering `test`.`person`... Creating new table... Created new table test._person_new OK. Altering new table... Altered `test`.`_person_new` OK. 2019-08-29T20:05:34 Creating triggers... 2019-08-29T20:05:34 Created triggers OK. 2019-08-29T20:05:34 Copying approximately 1 rows... 2019-08-29T20:05:34 Copied rows OK. 2019-08-29T20:05:34 Analyzing new table... 2019-08-29T20:05:34 Swapping tables... 2019-08-29T20:05:34 Swapped original and new tables OK. 2019-08-29T20:05:34 Dropping old table... 2019-08-29T20:05:34 Dropped old table `test`.`_person_old` OK. 2019-08-29T20:05:34 Dropping triggers... 2019-08-29T20:05:34 Dropped triggers OK. Successfully altered `test`.`person`.
這裏沒有insert ignore 是由於操做過程當中,沒有增刪改的記錄,並無觸發。這裏還能夠作下壓測,看記錄插入速度如何。it