Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

auto-increment: update doc for the new implementation #11798

Merged
merged 13 commits into from
Nov 7, 2022
26 changes: 26 additions & 0 deletions auto-increment.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@ aliases: ['/docs-cn/dev/auto-increment/']

出于性能原因,自增编号是系统批量分配给每台 TiDB 服务器的值(默认 3 万个值),因此自增编号能保证唯一性,但分配给 `INSERT` 语句的值仅在单台 TiDB 服务器上具有单调性。

> **注意:**
>
> 如果要求自增编号单调,并且 TiDB 版本在 v6.4.0 及以上,推荐使用 [MySQL 兼容模式](/auto-increment.md#mysql-兼容模式)。
tiancaiamao marked this conversation as resolved.
Show resolved Hide resolved

{{< copyable "sql" >}}

```sql
Expand Down Expand Up @@ -322,6 +326,28 @@ SELECT * FROM t;

从 v3.0.9 和 v4.0.rc-1 开始,和 MySQL 的行为类似,自增列隐式分配的值遵循 session 变量 `@@auto_increment_increment` 和 `@@auto_increment_offset` 的控制,其中自增列隐式分配的值 (ID) 将满足式子 `(ID - auto_increment_offset) % auto_increment_increment == 0`。

## MySQL 兼容模式

从 v6.4.0 开始,TiDB 实现了中心化分配的服务,可以支持 TiDB 实例不缓存数据,而是每次请求都访问中心化服务获取 ID。
tiancaiamao marked this conversation as resolved.
Show resolved Hide resolved
Oreoxmt marked this conversation as resolved.
Show resolved Hide resolved

当前中心化分配服务内置在 TiDB 进程,类似于 DDL Owner 的工作模式。有一个 TiDB 实例将充当“主”的角色提供 ID 分配服务,而其它的 TiDB 实例将充当“备”角色。当“主”节点发生故障时,会自动进行“主备切换",从而保证中心化服务的高可用。

MySQL 兼容模式的使用方式是,建表时将 `AUTO_ID_CACHE` 设置为 `1`:

```sql
CREATE TABLE t(a int AUTO_INCREMENT key) AUTO_ID_CACHE 1;
```


> **注意:**
>
> 在 TiDB 各个版本中,`AUTO_ID_CACHE` 设置为 `1` 都表明 TiDB 不再缓存 ID,但是不同版本的实现方式不一样:
>
> - 对于 TiDB v6.4.0 之前的版本,由于每次分配 ID 都需要通过一个 TiKV 事务完成 `AUTO_INCREMENT` 值的持久化修改,因此设置 `AUTO_ID_CACHE` 为 `1` 会出现性能下降。
> - 对于 v6.4.0 及以上版本,由于引入了中心化的分配服务,`AUTO_INCREMENT` 值的修改只是在服务进程中的一个内存操作,更加轻量。

使用 MySQL 兼容模式后,能保证 ID **唯一**、**单调递增**,行为几乎跟 MySQL 完成一致。即使跨 TiDB 实例访问,ID 也不会出现回退。只有当中心化服务的“主”异常崩溃时,才有可能造成少量 ID 不连续,出现空洞。这是因为主备切换时,“备”需要丢弃一部分之前的“主“可能分配出去的 ID,以保证 ID 不出现重复。

## 使用限制

目前在 TiDB 中使用 `AUTO_INCREMENT` 有以下限制:
Expand Down