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: add steps and notices to auto_increment and auto_random #19116

Merged
merged 9 commits into from
Jan 16, 2025
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions auto-increment.md
Original file line number Diff line number Diff line change
Expand Up @@ -334,6 +334,7 @@ SELECT * FROM t;
在一些场景中,你可能需要清除自增 ID 缓存,以保证数据一致性。例如:

- 使用 [Data Migration (DM)](/dm/dm-overview.md) 进行增量同步,当同步结束后,下游 TiDB 的数据写入方式将从 DM 切换回正常的业务数据写入,此时自增列 ID 的写入模式通常由显式写入转换成隐式分配。
- TiDB Lightning 完成数据导入后会自动清除自增 ID 缓存,但 TiCDC 在增量同步后不会自动清除。因此,在停止 TiCDC 并进行主备切换之前,需要手动清除下游集群的自增 ID 缓存。
- 当业务同时使用了显式写入和隐式分配时,需要清除自增 ID 缓存,以防止后续隐式分配的自增 ID 与已显式写入的 ID 发生冲突,导致主键冲突错误。具体场景参考[唯一性保证](/auto-increment.md#唯一性保证)。

你可以执行 `ALTER TABLE` 语句设置 `AUTO_INCREMENT = 0` 来清除集群中所有 TiDB 节点的自增 ID 缓存。例如:
Expand Down
27 changes: 27 additions & 0 deletions auto-random.md
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,33 @@ SHOW WARNINGS;

`AUTO_RANDOM` 列隐式分配的值和自增列类似,也遵循 session 变量 [`auto_increment_increment`](/system-variables.md#auto_increment_increment) 和 [`auto_increment_offset`](/system-variables.md#auto_increment_offset) 的控制,其中隐式分配值的自增位 (ID) 满足等式 `(ID - auto_increment_offset) % auto_increment_increment == 0`。

## 清除自增 ID 缓存

显式插入数据到 `AUTO_RANDOM` 列的行为与 `AUTO_INCREMENT` 列一致,你也需要清除自增 ID 缓存。详细信息请参阅[清除自增 ID 缓存](/auto-increment.md#清除自增-id-缓存)。

你可以执行 `ALTER TABLE` 语句设置 `AUTO_RANDOM_BASE = 0` 来清除集群中所有 TiDB 节点的自增 ID 缓存。例如:
hfxsd marked this conversation as resolved.
Show resolved Hide resolved

```sql
ALTER TABLE t AUTO_RANDOM_BASE=0;
```

```
Query OK, 0 rows affected, 1 warning (0.52 sec)
```

```sql
SHOW WARNINGS;
```

```
+---------+------+-------------------------------------------------------------------------+
| Level | Code | Message |
+---------+------+-------------------------------------------------------------------------+
| Warning | 1105 | Can't reset AUTO_INCREMENT to 0 without FORCE option, using 101 instead |
+---------+------+-------------------------------------------------------------------------+
1 row in set (0.00 sec)
```

## 使用限制

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