# [Know Issue] 执行 replace into select from 语句之后报 ERROR 1105 (HY000): runtime error: index out of range

## Key Words

runtime error, index out of range, 1105, replace into, insert into

## Description

程序偶尔会报 ERROR 1105 (HY000): runtime error: index out of range [1] with length 1。  
深入观察发现，在执行 replace into select from 之后再执行 insert 就会报这个错误。
示例:

```sql
mysql> CREATE TABLE `t_securities` (
    ->   `id` bigint NOT NULL AUTO_INCREMENT COMMENT 'id',
    ->   `security_id` varchar(8) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL ,
    ->   `market_id` smallint DEFAULT NULL ,
    ->   `security_type` int DEFAULT NULL ,
    ->   PRIMARY KEY (`id`) USING BTREE,
    ->   UNIQUE KEY `unique_securityId_marketId` (`security_id`,`market_id`)
    -> ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin  ;
Query OK, 0 rows affected (0.11 sec)

mysql> INSERT INTO t_securities (security_id, market_id, security_type) values    ("1", 2,7), ("7", 1,7) ON DUPLICATE KEY UPDATE         security_type = VALUES(security_type);
Query OK, 2 rows affected (0.01 sec)
Records: 2  Duplicates: 0  Warnings: 0

mysql> replace INTO t_securities (security_id, market_id, security_type) select security_id+1, 1, security_type from t_securities  where security_id="7";
Query OK, 1 row affected (0.01 sec)
Records: 1  Duplicates: 0  Warnings: 0

mysql> INSERT INTO t_securities (security_id, market_id, security_type) values    ("1", 2,7), ("7", 1,7) ON DUPLICATE KEY UPDATE         security_type = VALUES(security_type);
ERROR 1105 (HY000): runtime error: index out of range [1] with length 1
```

## Root Cause

ReplaceExec 在 [Close](https://github.com/pingcap/tidb/blob/5c04d78f29e8f2945bbf66a4a4ee7ed29ac3a056/executor/replace.go#L44) 的时候没有重置 session 中的 CurrInsertBatchExtraCols 变量，导致在下次执行 insert 的时候会[判断并获取该变量](https://github.com/pingcap/tidb/blob/f600fc694f98b30f90c5723ae29c6dbb9da6dbbf/executor/insert.go#L206)而报错，如果之前执行过类似 `replace into xxx select from xxx` 就有可能触发这个问题。  
相关 issue：[#40351](https://github.com/pingcap/tidb/issues/40351)

## Diagnostic Steps

1. 排查业务中 SQL 是否存在 replace into select 的语句。
2. 确认 replace into select 与 insert into 是否是在同一个数据库连接会话中执行的。

## Resolution

v5.3, v5.4, v6.1, v6.5 的下一个版本以及最新的 release 版本会修复。具体参考 [PR](https://github.com/pingcap/tidb/issues/40351) 合并情况。

## Workaround

N/A

## Affected Versions

v5.0.0 ~ v6.5.0
