canal icon indicating copy to clipboard operation
canal copied to clipboard

rdb-adapter按pk进行hash在unique约束下存在问题

Open flowell opened this issue 3 years ago • 1 comments

问题背景

rdb-adapter打开concurrent模式后,会按pk进行hash,并发地在目的库上重放SQL

问题描述

现有表A

id name
1 1
2 2

表A存在除主键外的唯一性约束(unique constraint),也就是说表A存在两个唯一性约束

pk: id
uk: name

现用户在源库执行SQL语句

delete from A where name = 1;
insert into A(name) values(1);

该SQL语句经binlog转到adapter的DML为

delete from A where id = 1;
insert into A(id, name) values(3,1);

因为这两个DML因为ID(pk)不一致,有可能hash到不同的桶中。导致insert先执行,insert执行时便报不唯一错误。

insert into A(id, name) values(3,1);    // unique constraint exception: duplicate entry
delete from A where id = 1;

我的看法

  1. 现有按pk计算hash值,本质上是对于唯一性约束计算hash值,单计算pk还不够,还需要计算uk。pk本质上也是uk的一个。
  2. 计算(pk, uk1, uk2, uk3, ...)每个唯一性约束列的分组值(hash到哪个桶),然后再合并多个结果值,时间复杂度O(N*M),N为一个批次中SingleDML的数量,M为唯一性约束的个数。

flowell avatar Jan 06 '22 02:01 flowell

不是delete from A where id = 1 而是 delete from A where id = 1 and name ="3";

lwd-coding avatar Jun 10 '24 03:06 lwd-coding