收到客户一个有意思的需求
- 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可随意定义