From acad2feb519414331fc4229b62ac4c4e563d0bd4 Mon Sep 17 00:00:00 2001 From: Arenatlx Date: Mon, 30 Mar 2020 01:17:12 -0500 Subject: [PATCH] table: fix multi nextval will return wrong result without sequence cache (#15728) --- ddl/sequence_test.go | 12 +++++++++++- table/tables/tables.go | 6 ++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/ddl/sequence_test.go b/ddl/sequence_test.go index 8270411914..e4e8de7a21 100644 --- a/ddl/sequence_test.go +++ b/ddl/sequence_test.go @@ -650,6 +650,16 @@ func (s *testSequenceSuite) TestSequenceFunction(c *C) { s.tk.MustExec("drop sequence if exists seq1") s.tk.MustExec("drop table if exists seq1") s.tk.MustExec("drop view if exists seq1") + + // test a bug found in ticase. + s.tk.MustExec("create sequence seq") + s.tk.MustQuery("select setval(seq, 10)").Check(testkit.Rows("10")) + s.tk.MustQuery("select setval(seq, 5)").Check(testkit.Rows("")) + s.tk.MustExec("drop sequence seq") + s.tk.MustExec("create sequence seq increment=-1") + s.tk.MustQuery("select setval(seq, -10)").Check(testkit.Rows("-10")) + s.tk.MustQuery("select setval(seq, -5)").Check(testkit.Rows("")) + s.tk.MustExec("drop sequence seq") } func (s *testSequenceSuite) TestInsertSequence(c *C) { @@ -713,7 +723,7 @@ func (s *testSequenceSuite) TestInsertSequence(c *C) { s.tk.MustExec("insert into t (id) values(-1),(default)") s.tk.MustQuery("select * from t").Check(testkit.Rows("-1 0", "4 5")) - // test sequence run out (overflow MaxInt64). + // test sequence run out (overflows MaxInt64). setSQL := "select setval(seq," + strconv.FormatInt(model.DefaultPositiveSequenceMaxValue+1, 10) + ")" s.tk.MustQuery(setSQL).Check(testkit.Rows("9223372036854775807")) err := s.tk.QueryToErr("select nextval(seq)") diff --git a/table/tables/tables.go b/table/tables/tables.go index 18601493b2..d05ac33428 100644 --- a/table/tables/tables.go +++ b/table/tables/tables.go @@ -1378,6 +1378,12 @@ func (t *TableCommon) SetSequenceVal(ctx interface{}, newVal int64, dbName, seqN return 0, false, err } } + // Record the current end after setval succeed. + // Consider the following case. + // create sequence seq + // setval(seq, 100) setval(seq, 50) + // Because no cache (base, end keep 0), so the second setval won't return NULL. + t.sequence.base, t.sequence.end = newVal, newVal return newVal, false, nil }