收到客戶一個有意思的需求
- A實例下的demo庫的t1要用復制同步到B實例,為了防止B實例會對這些數據做修改操作,需要限制B實例對t1表的修改操作.只允許查
第一想到的是用權限管理控制,收回B實例下所有用戶對t1表的權限,但這個操作在5.7里面十分繁瑣,且5.7不支持回收部分權限(8.0支持)
搜索網絡上的一些解決方案,發現用觸發器的方式十分合適,分別創建3個觸發器,來控制對t1表的insert,update,delete行為,這樣就做到了,A實例用復制同步時不受到影響但B實例想修改這些數據不允許操作
/* triggers */
delimiter //
DROP TRIGGER IF EXISTS stop_table_insert;
CREATE TRIGGER stop_table_insert
BEFORE INSERT ON `demo`.`t1`
FOR EACH ROW
BEGIN
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'This table Only replication synchronization is allowed, but data cannot be modified';
END;//
DROP TRIGGER IF EXISTS stop_table_update;
CREATE TRIGGER stop_table_update
BEFORE UPDATE ON `demo`.`t1`
FOR EACH ROW
BEGIN
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'This table Only replication synchronization is allowed, but data cannot be modified';
END;//
DROP TRIGGER IF EXISTS stop_table_delete;
CREATE TRIGGER stop_table_delete
BEFORE DELETE ON `demo`.`t1`
FOR EACH ROW
BEGIN
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'This table Only replication synchronization is allowed, but data cannot be modified';
END;//
delimiter ;
注意: SQLSTATE '45000'是用戶自定義錯誤狀態值的標准寫法,官方文檔描述是: To signal a generic SQLSTATE value, use '45000', which means “unhandled user-defined exception" ,MESSAGE_TEXT可隨意定義