Skip to content

Commit

Permalink
executor: replace should not change other rows when auto ID is out of…
Browse files Browse the repository at this point in the history
… range (#30301)
  • Loading branch information
tangenta committed Dec 2, 2021
1 parent 124f1fc commit 450d72f
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 0 deletions.
5 changes: 5 additions & 0 deletions executor/insert_common.go
Original file line number Diff line number Diff line change
Expand Up @@ -682,6 +682,11 @@ func setDatumAutoIDAndCast(ctx sessionctx.Context, d *types.Datum, id int64, col
d.SetAutoID(id, col.Flag)
var err error
*d, err = table.CastValue(ctx, *d, col.ToInfo(), false, false)
if err == nil && d.GetInt64() < id {
// Auto ID is out of range, the truncated ID is possible to duplicate with an existing ID.
// To prevent updating unrelated rows in the REPLACE statement, it is better to throw an error.
return autoid.ErrAutoincReadFailed
}
return err
}

Expand Down
15 changes: 15 additions & 0 deletions executor/insert_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1820,3 +1820,18 @@ func (s *testAutoRandomSuite) TestInsertIssue29892(c *C) {
c.Assert(err, NotNil)
c.Assert(strings.Contains(err.Error(), "Duplicate entry"), Equals, true)
}

// https://github.com/pingcap/tidb/issues/29483.
func (s *testSuite13) TestReplaceAllocatingAutoID(c *C) {
tk := testkit.NewTestKit(c, s.store)
tk.MustExec("drop database if exists replace_auto_id;")
tk.MustExec("create database replace_auto_id;")
tk.MustExec(`use replace_auto_id;`)

tk.MustExec("SET sql_mode='NO_ENGINE_SUBSTITUTION';")
tk.MustExec("DROP TABLE IF EXISTS t1;")
tk.MustExec("CREATE TABLE t1 (a tinyint not null auto_increment primary key, b char(20));")
tk.MustExec("INSERT INTO t1 VALUES (127,'maxvalue');")
// Note that this error is different from MySQL's duplicated primary key error.
tk.MustGetErrCode("REPLACE INTO t1 VALUES (0,'newmaxvalue');", errno.ErrAutoincReadFailed)
}

0 comments on commit 450d72f

Please sign in to comment.