diff --git a/executor/aggfuncs/aggfunc_test.go b/executor/aggfuncs/aggfunc_test.go index 55e6c951d7cdc..d106f6b824e62 100644 --- a/executor/aggfuncs/aggfunc_test.go +++ b/executor/aggfuncs/aggfunc_test.go @@ -34,6 +34,7 @@ import ( "github.com/pingcap/tidb/types/json" "github.com/pingcap/tidb/util/chunk" "github.com/pingcap/tidb/util/codec" + "github.com/pingcap/tidb/util/collate" "github.com/pingcap/tidb/util/hack" "github.com/pingcap/tidb/util/mock" "github.com/pingcap/tidb/util/set" @@ -317,6 +318,7 @@ func testMergePartialResult(t *testing.T, p aggTest) { iter := chunk.NewIterator4Chunk(srcChk) args := []expression.Expression{&expression.Column{RetType: p.dataType, Index: 0}} + ctor := collate.GetCollator(p.dataType.Collate) if p.funcName == ast.AggFuncGroupConcat { args = append(args, &expression.Constant{Value: types.NewStringDatum(separator), RetType: types.NewFieldType(mysql.TypeString)}) } @@ -359,7 +361,7 @@ func testMergePartialResult(t *testing.T, p aggTest) { if p.funcName == ast.AggFuncJsonArrayagg { dt = resultChk.GetRow(0).GetDatum(0, types.NewFieldType(mysql.TypeJSON)) } - result, err := dt.CompareDatum(ctx.GetSessionVars().StmtCtx, &p.results[0]) + result, err := dt.Compare(ctx.GetSessionVars().StmtCtx, &p.results[0], ctor) require.NoError(t, err) require.Equalf(t, 0, result, "%v != %v", dt.String(), p.results[0]) @@ -386,7 +388,7 @@ func testMergePartialResult(t *testing.T, p aggTest) { if p.funcName == ast.AggFuncJsonArrayagg { dt = resultChk.GetRow(0).GetDatum(0, types.NewFieldType(mysql.TypeJSON)) } - result, err = dt.CompareDatum(ctx.GetSessionVars().StmtCtx, &p.results[1]) + result, err = dt.Compare(ctx.GetSessionVars().StmtCtx, &p.results[1], ctor) require.NoError(t, err) require.Equalf(t, 0, result, "%v != %v", dt.String(), p.results[1]) _, err = finalFunc.MergePartialResult(ctx, partialResult, finalPr) @@ -409,7 +411,7 @@ func testMergePartialResult(t *testing.T, p aggTest) { if p.funcName == ast.AggFuncJsonArrayagg { dt = resultChk.GetRow(0).GetDatum(0, types.NewFieldType(mysql.TypeJSON)) } - result, err = dt.CompareDatum(ctx.GetSessionVars().StmtCtx, &p.results[2]) + result, err = dt.Compare(ctx.GetSessionVars().StmtCtx, &p.results[2], ctor) require.NoError(t, err) require.Equalf(t, 0, result, "%v != %v", dt.String(), p.results[2]) } @@ -447,6 +449,7 @@ func testMultiArgsMergePartialResult(t *testing.T, ctx sessionctx.Context, p mul {Expr: args[0], Desc: true}, } } + ctor := collate.GetCollator(args[0].GetType().Collate) partialDesc, finalDesc := desc.Split([]int{0, 1}) // build partial func for partial phase. @@ -467,7 +470,7 @@ func testMultiArgsMergePartialResult(t *testing.T, ctx sessionctx.Context, p mul err = partialFunc.AppendFinalResult2Chunk(ctx, partialResult, resultChk) require.NoError(t, err) dt := resultChk.GetRow(0).GetDatum(0, p.retType) - result, err := dt.CompareDatum(ctx.GetSessionVars().StmtCtx, &p.results[0]) + result, err := dt.Compare(ctx.GetSessionVars().StmtCtx, &p.results[0], ctor) require.NoError(t, err) require.Zero(t, result) @@ -488,7 +491,7 @@ func testMultiArgsMergePartialResult(t *testing.T, ctx sessionctx.Context, p mul err = partialFunc.AppendFinalResult2Chunk(ctx, partialResult, resultChk) require.NoError(t, err) dt = resultChk.GetRow(0).GetDatum(0, p.retType) - result, err = dt.CompareDatum(ctx.GetSessionVars().StmtCtx, &p.results[1]) + result, err = dt.Compare(ctx.GetSessionVars().StmtCtx, &p.results[1], ctor) require.NoError(t, err) require.Zero(t, result) _, err = finalFunc.MergePartialResult(ctx, partialResult, finalPr) @@ -499,7 +502,7 @@ func testMultiArgsMergePartialResult(t *testing.T, ctx sessionctx.Context, p mul require.NoError(t, err) dt = resultChk.GetRow(0).GetDatum(0, p.retType) - result, err = dt.CompareDatum(ctx.GetSessionVars().StmtCtx, &p.results[2]) + result, err = dt.Compare(ctx.GetSessionVars().StmtCtx, &p.results[2], ctor) require.NoError(t, err) require.Zero(t, result) } @@ -570,6 +573,7 @@ func testAggFunc(t *testing.T, p aggTest) { ctx := mock.NewContext() args := []expression.Expression{&expression.Column{RetType: p.dataType, Index: 0}} + ctor := collate.GetCollator(p.dataType.Collate) if p.funcName == ast.AggFuncGroupConcat { args = append(args, &expression.Constant{Value: types.NewStringDatum(separator), RetType: types.NewFieldType(mysql.TypeString)}) } @@ -596,7 +600,7 @@ func testAggFunc(t *testing.T, p aggTest) { err = finalFunc.AppendFinalResult2Chunk(ctx, finalPr, resultChk) require.NoError(t, err) dt := resultChk.GetRow(0).GetDatum(0, desc.RetTp) - result, err := dt.CompareDatum(ctx.GetSessionVars().StmtCtx, &p.results[1]) + result, err := dt.Compare(ctx.GetSessionVars().StmtCtx, &p.results[1], ctor) require.NoError(t, err) require.Equalf(t, 0, result, "%v != %v", dt.String(), p.results[1]) @@ -606,7 +610,7 @@ func testAggFunc(t *testing.T, p aggTest) { err = finalFunc.AppendFinalResult2Chunk(ctx, finalPr, resultChk) require.NoError(t, err) dt = resultChk.GetRow(0).GetDatum(0, desc.RetTp) - result, err = dt.CompareDatum(ctx.GetSessionVars().StmtCtx, &p.results[0]) + result, err = dt.Compare(ctx.GetSessionVars().StmtCtx, &p.results[0], ctor) require.NoError(t, err) require.Equalf(t, 0, result, "%v != %v", dt.String(), p.results[0]) @@ -639,7 +643,7 @@ func testAggFunc(t *testing.T, p aggTest) { err = finalFunc.AppendFinalResult2Chunk(ctx, finalPr, resultChk) require.NoError(t, err) dt = resultChk.GetRow(0).GetDatum(0, desc.RetTp) - result, err = dt.CompareDatum(ctx.GetSessionVars().StmtCtx, &p.results[1]) + result, err = dt.Compare(ctx.GetSessionVars().StmtCtx, &p.results[1], ctor) require.NoError(t, err) require.Equalf(t, 0, result, "%v != %v", dt.String(), p.results[1]) @@ -649,7 +653,7 @@ func testAggFunc(t *testing.T, p aggTest) { err = finalFunc.AppendFinalResult2Chunk(ctx, finalPr, resultChk) require.NoError(t, err) dt = resultChk.GetRow(0).GetDatum(0, desc.RetTp) - result, err = dt.CompareDatum(ctx.GetSessionVars().StmtCtx, &p.results[0]) + result, err = dt.Compare(ctx.GetSessionVars().StmtCtx, &p.results[0], ctor) require.NoError(t, err) require.Equalf(t, 0, result, "%v != %v", dt.String(), p.results[0]) } @@ -658,6 +662,7 @@ func testAggFuncWithoutDistinct(t *testing.T, p aggTest) { srcChk := p.genSrcChk() args := []expression.Expression{&expression.Column{RetType: p.dataType, Index: 0}} + ctor := collate.GetCollator(p.dataType.Collate) if p.funcName == ast.AggFuncGroupConcat { args = append(args, &expression.Constant{Value: types.NewStringDatum(separator), RetType: types.NewFieldType(mysql.TypeString)}) } @@ -685,7 +690,7 @@ func testAggFuncWithoutDistinct(t *testing.T, p aggTest) { err = finalFunc.AppendFinalResult2Chunk(ctx, finalPr, resultChk) require.NoError(t, err) dt := resultChk.GetRow(0).GetDatum(0, desc.RetTp) - result, err := dt.CompareDatum(ctx.GetSessionVars().StmtCtx, &p.results[1]) + result, err := dt.Compare(ctx.GetSessionVars().StmtCtx, &p.results[1], ctor) require.NoError(t, err) require.Zerof(t, result, "%v != %v", dt.String(), p.results[1]) @@ -695,7 +700,7 @@ func testAggFuncWithoutDistinct(t *testing.T, p aggTest) { err = finalFunc.AppendFinalResult2Chunk(ctx, finalPr, resultChk) require.NoError(t, err) dt = resultChk.GetRow(0).GetDatum(0, desc.RetTp) - result, err = dt.CompareDatum(ctx.GetSessionVars().StmtCtx, &p.results[0]) + result, err = dt.Compare(ctx.GetSessionVars().StmtCtx, &p.results[0], ctor) require.NoError(t, err) require.Zerof(t, result, "%v != %v", dt.String(), p.results[0]) } @@ -749,6 +754,7 @@ func testMultiArgsAggFunc(t *testing.T, ctx sessionctx.Context, p multiArgsAggTe {Expr: args[0], Desc: true}, } } + ctor := collate.GetCollator(args[0].GetType().Collate) finalFunc := aggfuncs.Build(ctx, desc, 0) finalPr, _ := finalFunc.AllocPartialResult() resultChk := chunk.NewChunkWithCapacity([]*types.FieldType{desc.RetTp}, 1) @@ -762,7 +768,7 @@ func testMultiArgsAggFunc(t *testing.T, ctx sessionctx.Context, p multiArgsAggTe err = finalFunc.AppendFinalResult2Chunk(ctx, finalPr, resultChk) require.NoError(t, err) dt := resultChk.GetRow(0).GetDatum(0, desc.RetTp) - result, err := dt.CompareDatum(ctx.GetSessionVars().StmtCtx, &p.results[1]) + result, err := dt.Compare(ctx.GetSessionVars().StmtCtx, &p.results[1], ctor) require.NoError(t, err) require.Zerof(t, result, "%v != %v", dt.String(), p.results[1]) @@ -772,7 +778,7 @@ func testMultiArgsAggFunc(t *testing.T, ctx sessionctx.Context, p multiArgsAggTe err = finalFunc.AppendFinalResult2Chunk(ctx, finalPr, resultChk) require.NoError(t, err) dt = resultChk.GetRow(0).GetDatum(0, desc.RetTp) - result, err = dt.CompareDatum(ctx.GetSessionVars().StmtCtx, &p.results[0]) + result, err = dt.Compare(ctx.GetSessionVars().StmtCtx, &p.results[0], ctor) require.NoError(t, err) require.Zerof(t, result, "%v != %v", dt.String(), p.results[0]) @@ -805,7 +811,7 @@ func testMultiArgsAggFunc(t *testing.T, ctx sessionctx.Context, p multiArgsAggTe err = finalFunc.AppendFinalResult2Chunk(ctx, finalPr, resultChk) require.NoError(t, err) dt = resultChk.GetRow(0).GetDatum(0, desc.RetTp) - result, err = dt.CompareDatum(ctx.GetSessionVars().StmtCtx, &p.results[1]) + result, err = dt.Compare(ctx.GetSessionVars().StmtCtx, &p.results[1], ctor) require.NoError(t, err) require.Zerof(t, result, "%v != %v", dt.String(), p.results[1]) @@ -815,7 +821,7 @@ func testMultiArgsAggFunc(t *testing.T, ctx sessionctx.Context, p multiArgsAggTe err = finalFunc.AppendFinalResult2Chunk(ctx, finalPr, resultChk) require.NoError(t, err) dt = resultChk.GetRow(0).GetDatum(0, desc.RetTp) - result, err = dt.CompareDatum(ctx.GetSessionVars().StmtCtx, &p.results[0]) + result, err = dt.Compare(ctx.GetSessionVars().StmtCtx, &p.results[0], ctor) require.NoError(t, err) require.Zero(t, result) } diff --git a/executor/aggregate_test.go b/executor/aggregate_test.go index 2a9360421f704..2296ff2d2cb91 100644 --- a/executor/aggregate_test.go +++ b/executor/aggregate_test.go @@ -651,15 +651,6 @@ func TestGroupConcatAggr(t *testing.T) { rows.Check(testkit.Rows("01234567", "12345")) } -func fillData(tk *testkit.TestKit, table string) { - tk.MustExec("use test") - tk.MustExec(fmt.Sprintf("create table %s(id int not null default 1, name varchar(255), PRIMARY KEY(id));", table)) - - // insert data - tk.MustExec(fmt.Sprintf("insert INTO %s VALUES (1, \"hello\");", table)) - tk.MustExec(fmt.Sprintf("insert into %s values (2, \"hello\");", table)) -} - func TestSelectDistinct(t *testing.T) { t.Parallel() store, clean := testkit.CreateMockStore(t) diff --git a/executor/analyze_test.go b/executor/analyze_test.go index fe067c5f46423..f8c574f36d53a 100644 --- a/executor/analyze_test.go +++ b/executor/analyze_test.go @@ -371,7 +371,7 @@ func (s *testFastAnalyze) TestAnalyzeFastSample(c *C) { samples := mockExec.Collectors[i].Samples c.Assert(len(samples), Equals, 20) for j := 1; j < 20; j++ { - cmp, err := samples[j].Value.CompareDatum(tk.Se.GetSessionVars().StmtCtx, &samples[j-1].Value) + cmp, err := samples[j].Value.Compare(tk.Se.GetSessionVars().StmtCtx, &samples[j-1].Value, collate.GetBinaryCollator()) c.Assert(err, IsNil) c.Assert(cmp, Greater, 0) } @@ -381,7 +381,7 @@ func (s *testFastAnalyze) TestAnalyzeFastSample(c *C) { func checkHistogram(sc *stmtctx.StatementContext, hg *statistics.Histogram) (bool, error) { for i := 0; i < len(hg.Buckets); i++ { lower, upper := hg.GetLower(i), hg.GetUpper(i) - cmp, err := upper.CompareDatum(sc, lower) + cmp, err := upper.Compare(sc, lower, collate.GetBinaryCollator()) if cmp < 0 || err != nil { return false, err } @@ -389,7 +389,7 @@ func checkHistogram(sc *stmtctx.StatementContext, hg *statistics.Histogram) (boo continue } previousUpper := hg.GetUpper(i - 1) - cmp, err = lower.CompareDatum(sc, previousUpper) + cmp, err = lower.Compare(sc, previousUpper, collate.GetBinaryCollator()) if cmp <= 0 || err != nil { return false, err } diff --git a/executor/builder.go b/executor/builder.go index c277eb8e91b79..d75299884ca0c 100644 --- a/executor/builder.go +++ b/executor/builder.go @@ -4260,7 +4260,8 @@ func (b *executorBuilder) buildShuffle(v *plannercore.PhysicalShuffle) *ShuffleE for j, dataSource := range v.DataSources { stub := plannercore.PhysicalShuffleReceiverStub{ - Receiver: (unsafe.Pointer)(receivers[j]), + Receiver: (unsafe.Pointer)(receivers[j]), + DataSource: dataSource, }.Init(b.ctx, dataSource.Stats(), dataSource.SelectBlockOffset(), nil) stub.SetSchema(dataSource.Schema()) v.Tails[j].SetChildren(stub) diff --git a/executor/executor_test.go b/executor/executor_test.go index cff889d7e39c6..b3e9d613c9c53 100644 --- a/executor/executor_test.go +++ b/executor/executor_test.go @@ -66,6 +66,7 @@ import ( "github.com/pingcap/tidb/table" "github.com/pingcap/tidb/table/tables" "github.com/pingcap/tidb/tablecodec" + testkit2 "github.com/pingcap/tidb/testkit" "github.com/pingcap/tidb/types" "github.com/pingcap/tidb/util" "github.com/pingcap/tidb/util/admin" @@ -81,6 +82,7 @@ import ( "github.com/pingcap/tidb/util/testutil" "github.com/pingcap/tidb/util/timeutil" "github.com/pingcap/tipb/go-tipb" + "github.com/stretchr/testify/require" "github.com/tikv/client-go/v2/oracle" "github.com/tikv/client-go/v2/testutils" "github.com/tikv/client-go/v2/tikv" @@ -112,7 +114,6 @@ var _ = SerialSuites(&testSuiteJoinSerial{&baseTestSuite{}}) var _ = Suite(&testSuite6{&baseTestSuite{}}) var _ = Suite(&testSuite7{&baseTestSuite{}}) var _ = Suite(&testSuite8{&baseTestSuite{}}) -var _ = Suite(&testBypassSuite{}) var _ = Suite(&testUpdateSuite{}) var _ = Suite(&testPointGetSuite{}) var _ = SerialSuites(&testRecoverTable{}) @@ -617,35 +618,33 @@ type testCase struct { } func checkCases(tests []testCase, ld *executor.LoadDataInfo, - c *C, tk *testkit.TestKit, ctx sessionctx.Context, selectSQL, deleteSQL string) { + t *testing.T, tk *testkit2.TestKit, ctx sessionctx.Context, selectSQL, deleteSQL string) { origin := ld.IgnoreLines for _, tt := range tests { ld.IgnoreLines = origin - c.Assert(ctx.NewTxn(context.Background()), IsNil) + require.Nil(t, ctx.NewTxn(context.Background())) ctx.GetSessionVars().StmtCtx.DupKeyAsWarning = true ctx.GetSessionVars().StmtCtx.BadNullAsWarning = true ctx.GetSessionVars().StmtCtx.InLoadDataStmt = true ctx.GetSessionVars().StmtCtx.InDeleteStmt = false data, reachLimit, err1 := ld.InsertData(context.Background(), tt.data1, tt.data2) - c.Assert(err1, IsNil) - c.Assert(reachLimit, IsFalse) + require.NoError(t, err1) + require.False(t, reachLimit) err1 = ld.CheckAndInsertOneBatch(context.Background(), ld.GetRows(), ld.GetCurBatchCnt()) - c.Assert(err1, IsNil) + require.NoError(t, err1) ld.SetMaxRowsInBatch(20000) if tt.restData == nil { - c.Assert(data, HasLen, 0, - Commentf("data1:%v, data2:%v, data:%v", string(tt.data1), string(tt.data2), string(data))) + require.Len(t, data, 0, "data1:%v, data2:%v, data:%v", string(tt.data1), string(tt.data2), string(data)) } else { - c.Assert(data, DeepEquals, tt.restData, - Commentf("data1:%v, data2:%v, data:%v", string(tt.data1), string(tt.data2), string(data))) + require.Equal(t, tt.restData, data, "data1:%v, data2:%v, data:%v", string(tt.data1), string(tt.data2), string(data)) } ld.SetMessage() - tk.CheckLastMessage(tt.expectedMsg) + require.Equal(t, tt.expectedMsg, tk.Session().LastMessage()) ctx.StmtCommit() txn, err := ctx.Txn(true) - c.Assert(err, IsNil) + require.NoError(t, err) err = txn.Commit(context.Background()) - c.Assert(err, IsNil) + require.NoError(t, err) r := tk.MustQuery(selectSQL) r.Check(testutil.RowsWithSep("|", tt.expected...)) tk.MustExec(deleteSQL) diff --git a/executor/main_test.go b/executor/main_test.go index a0ecb2044be78..1e02955ee8e4c 100644 --- a/executor/main_test.go +++ b/executor/main_test.go @@ -15,11 +15,13 @@ package executor_test import ( + "fmt" "os" "testing" "github.com/pingcap/tidb/config" "github.com/pingcap/tidb/meta/autoid" + "github.com/pingcap/tidb/testkit" "github.com/pingcap/tidb/testkit/testdata" "github.com/pingcap/tidb/testkit/testmain" "github.com/pingcap/tidb/util/testbridge" @@ -64,3 +66,12 @@ func TestMain(m *testing.M) { goleak.VerifyTestMain(testmain.WrapTestingM(m, callback), opts...) } + +func fillData(tk *testkit.TestKit, table string) { + tk.MustExec("use test") + tk.MustExec(fmt.Sprintf("create table %s(id int not null default 1, name varchar(255), PRIMARY KEY(id));", table)) + + // insert data + tk.MustExec(fmt.Sprintf("insert INTO %s VALUES (1, \"hello\");", table)) + tk.MustExec(fmt.Sprintf("insert into %s values (2, \"hello\");", table)) +} diff --git a/executor/write_serial_test.go b/executor/write_serial_test.go new file mode 100644 index 0000000000000..440ecbeb177e2 --- /dev/null +++ b/executor/write_serial_test.go @@ -0,0 +1,389 @@ +// Copyright 2021 PingCAP, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package executor_test + +import ( + "testing" + + "github.com/pingcap/tidb/config" + "github.com/pingcap/tidb/parser/mysql" + "github.com/pingcap/tidb/planner/core" + "github.com/pingcap/tidb/sessionctx/variable" + "github.com/pingcap/tidb/testkit" + "github.com/pingcap/tidb/types" + "github.com/pingcap/tidb/util/collate" + "github.com/stretchr/testify/require" +) + +func TestUpdate(t *testing.T) { + store, clean := testkit.CreateMockStore(t) + defer clean() + tk := testkit.NewTestKit(t, store) + tk.MustExec("use test") + fillData(tk, "update_test") + + updateStr := `UPDATE update_test SET name = "abc" where id > 0;` + tk.MustExec(updateStr) + tk.CheckExecResult(2, 0) + require.Equal(t, tk.Session().LastMessage(), "Rows matched: 2 Changed: 2 Warnings: 0") + + // select data + tk.MustExec("begin") + r := tk.MustQuery(`SELECT * from update_test limit 2;`) + r.Check(testkit.Rows("1 abc", "2 abc")) + tk.MustExec("commit") + + tk.MustExec(`UPDATE update_test SET name = "foo"`) + tk.CheckExecResult(2, 0) + require.Equal(t, tk.Session().LastMessage(), "Rows matched: 2 Changed: 2 Warnings: 0") + + // table option is auto-increment + tk.MustExec("begin") + tk.MustExec("drop table if exists update_test;") + tk.MustExec("commit") + tk.MustExec("begin") + tk.MustExec("create table update_test(id int not null auto_increment, name varchar(255), primary key(id))") + tk.MustExec("insert into update_test(name) values ('aa')") + tk.MustExec("update update_test set id = 8 where name = 'aa'") + require.Equal(t, tk.Session().LastMessage(), "Rows matched: 1 Changed: 1 Warnings: 0") + tk.MustExec("insert into update_test(name) values ('bb')") + tk.MustExec("commit") + tk.MustExec("begin") + r = tk.MustQuery("select * from update_test;") + r.Check(testkit.Rows("8 aa", "9 bb")) + tk.MustExec("commit") + + tk.MustExec("begin") + tk.MustExec("drop table if exists update_test;") + tk.MustExec("commit") + tk.MustExec("begin") + tk.MustExec("create table update_test(id int not null auto_increment, name varchar(255), index(id))") + tk.MustExec("insert into update_test(name) values ('aa')") + _, err := tk.Exec("update update_test set id = null where name = 'aa'") + require.EqualError(t, err, "[table:1048]Column 'id' cannot be null") + + tk.MustExec("drop table update_test") + tk.MustExec("create table update_test(id int)") + tk.MustExec("begin") + tk.MustExec("insert into update_test(id) values (1)") + tk.MustExec("update update_test set id = 2 where id = 1 limit 1") + require.Equal(t, tk.Session().LastMessage(), "Rows matched: 1 Changed: 1 Warnings: 0") + r = tk.MustQuery("select * from update_test;") + r.Check(testkit.Rows("2")) + tk.MustExec("commit") + + // Test that in a transaction, when a constraint failed in an update statement, the record is not inserted. + tk.MustExec("create table update_unique (id int primary key, name int unique)") + tk.MustExec("insert update_unique values (1, 1), (2, 2);") + tk.MustExec("begin") + _, err = tk.Exec("update update_unique set name = 1 where id = 2") + require.Error(t, err) + tk.MustExec("commit") + tk.MustQuery("select * from update_unique").Check(testkit.Rows("1 1", "2 2")) + + // test update ignore for pimary key + tk.MustExec("drop table if exists t;") + tk.MustExec("create table t(a bigint, primary key (a));") + tk.MustExec("insert into t values (1)") + tk.MustExec("insert into t values (2)") + _, err = tk.Exec("update ignore t set a = 1 where a = 2;") + require.NoError(t, err) + require.Equal(t, tk.Session().LastMessage(), "Rows matched: 1 Changed: 0 Warnings: 1") + r = tk.MustQuery("SHOW WARNINGS;") + r.Check(testkit.Rows("Warning 1062 Duplicate entry '1' for key 'PRIMARY'")) + tk.MustQuery("select * from t").Check(testkit.Rows("1", "2")) + + // test update ignore for truncate as warning + _, err = tk.Exec("update ignore t set a = 1 where a = (select '2a')") + require.NoError(t, err) + r = tk.MustQuery("SHOW WARNINGS;") + r.Check(testkit.Rows("Warning 1292 Truncated incorrect DOUBLE value: '2a'", "Warning 1292 Truncated incorrect DOUBLE value: '2a'", "Warning 1062 Duplicate entry '1' for key 'PRIMARY'")) + + tk.MustExec("update ignore t set a = 42 where a = 2;") + tk.MustQuery("select * from t").Check(testkit.Rows("1", "42")) + + // test update ignore for unique key + tk.MustExec("drop table if exists t;") + tk.MustExec("create table t(a bigint, unique key I_uniq (a));") + tk.MustExec("insert into t values (1)") + tk.MustExec("insert into t values (2)") + _, err = tk.Exec("update ignore t set a = 1 where a = 2;") + require.NoError(t, err) + require.Equal(t, tk.Session().LastMessage(), "Rows matched: 1 Changed: 0 Warnings: 1") + r = tk.MustQuery("SHOW WARNINGS;") + r.Check(testkit.Rows("Warning 1062 Duplicate entry '1' for key 'I_uniq'")) + tk.MustQuery("select * from t").Check(testkit.Rows("1", "2")) + + // test issue21965 + tk.MustExec("drop table if exists t;") + tk.MustExec("set @@session.tidb_enable_list_partition = ON") + tk.MustExec("create table t (a int) partition by list (a) (partition p0 values in (0,1));") + tk.MustExec("insert ignore into t values (1);") + tk.MustExec("update ignore t set a=2 where a=1;") + require.Equal(t, tk.Session().LastMessage(), "Rows matched: 1 Changed: 0 Warnings: 0") + tk.MustExec("drop table if exists t;") + tk.MustExec("create table t (a int key) partition by list (a) (partition p0 values in (0,1));") + tk.MustExec("insert ignore into t values (1);") + tk.MustExec("update ignore t set a=2 where a=1;") + require.Equal(t, tk.Session().LastMessage(), "Rows matched: 1 Changed: 0 Warnings: 0") + + tk.MustExec("drop table if exists t") + tk.MustExec("create table t(id integer auto_increment, t1 datetime, t2 datetime, primary key (id))") + tk.MustExec("insert into t(t1, t2) values('2000-10-01 01:01:01', '2017-01-01 10:10:10')") + tk.MustQuery("select * from t").Check(testkit.Rows("1 2000-10-01 01:01:01 2017-01-01 10:10:10")) + tk.MustExec("update t set t1 = '2017-10-01 10:10:11', t2 = date_add(t1, INTERVAL 10 MINUTE) where id = 1") + require.Equal(t, tk.Session().LastMessage(), "Rows matched: 1 Changed: 1 Warnings: 0") + tk.MustQuery("select * from t").Check(testkit.Rows("1 2017-10-01 10:10:11 2000-10-01 01:11:01")) + + // for issue #5132 + tk.MustExec("CREATE TABLE `tt1` (" + + "`a` int(11) NOT NULL," + + "`b` varchar(32) DEFAULT NULL," + + "`c` varchar(32) DEFAULT NULL," + + "PRIMARY KEY (`a`)," + + "UNIQUE KEY `b_idx` (`b`)" + + ") ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;") + tk.MustExec("insert into tt1 values(1, 'a', 'a');") + tk.MustExec("insert into tt1 values(2, 'd', 'b');") + r = tk.MustQuery("select * from tt1;") + r.Check(testkit.Rows("1 a a", "2 d b")) + tk.MustExec("update tt1 set a=5 where c='b';") + require.Equal(t, tk.Session().LastMessage(), "Rows matched: 1 Changed: 1 Warnings: 0") + r = tk.MustQuery("select * from tt1;") + r.Check(testkit.Rows("1 a a", "5 d b")) + + // Automatic Updating for TIMESTAMP + tk.MustExec("CREATE TABLE `tsup` (" + + "`a` int," + + "`ts` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP," + + "KEY `idx` (`ts`)" + + ");") + tk.MustExec("set @orig_sql_mode=@@sql_mode; set @@sql_mode='';") + tk.MustExec("insert into tsup values(1, '0000-00-00 00:00:00');") + tk.MustExec("update tsup set a=5;") + require.Equal(t, tk.Session().LastMessage(), "Rows matched: 1 Changed: 1 Warnings: 0") + r1 := tk.MustQuery("select ts from tsup use index (idx);") + r2 := tk.MustQuery("select ts from tsup;") + r1.Check(r2.Rows()) + tk.MustExec("update tsup set ts='2019-01-01';") + tk.MustQuery("select ts from tsup;").Check(testkit.Rows("2019-01-01 00:00:00")) + tk.MustExec("set @@sql_mode=@orig_sql_mode;") + + // issue 5532 + tk.MustExec("create table decimals (a decimal(20, 0) not null)") + tk.MustExec("insert into decimals values (201)") + // A warning rather than data truncated error. + tk.MustExec("update decimals set a = a + 1.23;") + require.Equal(t, tk.Session().LastMessage(), "Rows matched: 1 Changed: 1 Warnings: 1") + tk.MustQuery("show warnings").Check(testkit.Rows("Warning 1292 Truncated incorrect DECIMAL value: '202.23'")) + r = tk.MustQuery("select * from decimals") + r.Check(testkit.Rows("202")) + + tk.MustExec("drop table t") + tk.MustExec("CREATE TABLE `t` ( `c1` year DEFAULT NULL, `c2` year DEFAULT NULL, `c3` date DEFAULT NULL, `c4` datetime DEFAULT NULL, KEY `idx` (`c1`,`c2`))") + _, err = tk.Exec("UPDATE t SET c2=16777215 WHERE c1>= -8388608 AND c1 < -9 ORDER BY c1 LIMIT 2") + require.NoError(t, err) + + tk.MustGetErrCode("update (select * from t) t set c1 = 1111111", mysql.ErrNonUpdatableTable) + + // test update ignore for bad null error + tk.MustExec("drop table if exists t;") + tk.MustExec(`create table t (i int not null default 10)`) + tk.MustExec("insert into t values (1)") + tk.MustExec("update ignore t set i = null;") + require.Equal(t, tk.Session().LastMessage(), "Rows matched: 1 Changed: 1 Warnings: 1") + r = tk.MustQuery("SHOW WARNINGS;") + r.Check(testkit.Rows("Warning 1048 Column 'i' cannot be null")) + tk.MustQuery("select * from t").Check(testkit.Rows("0")) + + // issue 7237, update subquery table should be forbidden + tk.MustExec("drop table t") + tk.MustExec("create table t (k int, v int)") + _, err = tk.Exec("update t, (select * from t) as b set b.k = t.k") + require.EqualError(t, err, "[planner:1288]The target table b of the UPDATE is not updatable") + tk.MustExec("update t, (select * from t) as b set t.k = b.k") + + // issue 8045 + tk.MustExec("drop table if exists t1") + tk.MustExec(`CREATE TABLE t1 (c1 float)`) + tk.MustExec("INSERT INTO t1 SET c1 = 1") + tk.MustExec("UPDATE t1 SET c1 = 1.2 WHERE c1=1;") + require.Equal(t, tk.Session().LastMessage(), "Rows matched: 1 Changed: 1 Warnings: 0") + + // issue 8119 + tk.MustExec("drop table if exists t;") + tk.MustExec("create table t (c1 float(1,1));") + tk.MustExec("insert into t values (0.0);") + _, err = tk.Exec("update t set c1 = 2.0;") + require.True(t, types.ErrWarnDataOutOfRange.Equal(err)) + + tk.MustExec("drop table if exists t") + tk.MustExec("create table t(a datetime not null, b datetime)") + tk.MustExec("insert into t value('1999-12-12', '1999-12-13')") + tk.MustExec("set @orig_sql_mode=@@sql_mode; set @@sql_mode='';") + tk.MustQuery("select * from t").Check(testkit.Rows("1999-12-12 00:00:00 1999-12-13 00:00:00")) + tk.MustExec("update t set a = ''") + tk.MustQuery("select * from t").Check(testkit.Rows("0000-00-00 00:00:00 1999-12-13 00:00:00")) + tk.MustExec("update t set b = ''") + tk.MustQuery("select * from t").Check(testkit.Rows("0000-00-00 00:00:00 0000-00-00 00:00:00")) + tk.MustExec("set @@sql_mode=@orig_sql_mode;") + + tk.MustExec("create view v as select * from t") + _, err = tk.Exec("update v set a = '2000-11-11'") + require.EqualError(t, err, core.ErrViewInvalid.GenWithStackByArgs("test", "v").Error()) + tk.MustExec("drop view v") + + tk.MustExec("create sequence seq") + tk.MustGetErrCode("update seq set minvalue=1", mysql.ErrBadField) + tk.MustExec("drop sequence seq") + + tk.MustExec("drop table if exists t1, t2") + tk.MustExec("create table t1(a int, b int, c int, d int, e int, index idx(a))") + tk.MustExec("create table t2(a int, b int, c int)") + tk.MustExec("update t1 join t2 on t1.a=t2.a set t1.a=1 where t2.b=1 and t2.c=2") + + // Assign `DEFAULT` in `UPDATE` statement + tk.MustExec("drop table if exists t1, t2;") + tk.MustExec("create table t1 (a int default 1, b int default 2);") + tk.MustExec("insert into t1 values (10, 10), (20, 20);") + tk.MustExec("update t1 set a=default where b=10;") + tk.MustQuery("select * from t1;").Check(testkit.Rows("1 10", "20 20")) + tk.MustExec("update t1 set a=30, b=default where a=20;") + tk.MustQuery("select * from t1;").Check(testkit.Rows("1 10", "30 2")) + tk.MustExec("update t1 set a=default, b=default where a=30;") + tk.MustQuery("select * from t1;").Check(testkit.Rows("1 10", "1 2")) + tk.MustExec("insert into t1 values (40, 40)") + tk.MustExec("update t1 set a=default, b=default") + tk.MustQuery("select * from t1;").Check(testkit.Rows("1 2", "1 2", "1 2")) + tk.MustExec("update t1 set a=default(b), b=default(a)") + tk.MustQuery("select * from t1;").Check(testkit.Rows("2 1", "2 1", "2 1")) + // With generated columns + tk.MustExec("create table t2 (a int default 1, b int generated always as (-a) virtual, c int generated always as (-a) stored);") + tk.MustExec("insert into t2 values (10, default, default), (20, default, default)") + tk.MustExec("update t2 set b=default;") + tk.MustQuery("select * from t2;").Check(testkit.Rows("10 -10 -10", "20 -20 -20")) + tk.MustExec("update t2 set a=30, b=default where a=10;") + tk.MustQuery("select * from t2;").Check(testkit.Rows("30 -30 -30", "20 -20 -20")) + tk.MustExec("update t2 set c=default, a=40 where c=-20;") + tk.MustQuery("select * from t2;").Check(testkit.Rows("30 -30 -30", "40 -40 -40")) + tk.MustExec("update t2 set a=default, b=default, c=default where b=-30;") + tk.MustQuery("select * from t2;").Check(testkit.Rows("1 -1 -1", "40 -40 -40")) + tk.MustExec("update t2 set a=default(a), b=default, c=default;") + tk.MustQuery("select * from t2;").Check(testkit.Rows("1 -1 -1", "1 -1 -1")) + tk.MustGetErrCode("update t2 set b=default(a);", mysql.ErrBadGeneratedColumn) + tk.MustGetErrCode("update t2 set a=default(b), b=default(b);", mysql.ErrBadGeneratedColumn) + tk.MustGetErrCode("update t2 set a=default(a), c=default(c);", mysql.ErrBadGeneratedColumn) + tk.MustGetErrCode("update t2 set a=default(a), c=default(a);", mysql.ErrBadGeneratedColumn) + tk.MustExec("drop table t1, t2") +} + +func TestListColumnsPartitionWithGlobalIndex(t *testing.T) { + store, clean := testkit.CreateMockStore(t) + defer clean() + tk := testkit.NewTestKit(t, store) + tk.MustExec("use test") + tk.MustExec("set @@session.tidb_enable_list_partition = ON") + // Test generated column with global index + restoreConfig := config.RestoreFunc() + defer restoreConfig() + config.UpdateGlobal(func(conf *config.Config) { + conf.EnableGlobalIndex = true + }) + tableDefs := []string{ + // Test for virtual generated column with global index + `create table t (a varchar(10), b varchar(1) GENERATED ALWAYS AS (substr(a,1,1)) VIRTUAL) partition by list columns(b) (partition p0 values in ('a','c'), partition p1 values in ('b','d'));`, + // Test for stored generated column with global index + `create table t (a varchar(10), b varchar(1) GENERATED ALWAYS AS (substr(a,1,1)) STORED) partition by list columns(b) (partition p0 values in ('a','c'), partition p1 values in ('b','d'));`, + } + for _, tbl := range tableDefs { + tk.MustExec("drop table if exists t") + tk.MustExec(tbl) + tk.MustExec("alter table t add unique index (a)") + tk.MustExec("insert into t (a) values ('aaa'),('abc'),('acd')") + tk.MustQuery("select a from t partition (p0) order by a").Check(testkit.Rows("aaa", "abc", "acd")) + tk.MustQuery("select * from t where a = 'abc' order by a").Check(testkit.Rows("abc a")) + tk.MustExec("update t set a='bbb' where a = 'aaa'") + tk.MustExec("admin check table t") + tk.MustQuery("select a from t order by a").Check(testkit.Rows("abc", "acd", "bbb")) + // TODO: fix below test. + //tk.MustQuery("select a from t partition (p0) order by a").Check(testkit.Rows("abc", "acd")) + //tk.MustQuery("select a from t partition (p1) order by a").Check(testkit.Rows("bbb")) + tk.MustQuery("select * from t where a = 'bbb' order by a").Check(testkit.Rows("bbb b")) + // Test insert meet duplicate error. + _, err := tk.Exec("insert into t (a) values ('abc')") + require.Error(t, err) + // Test insert on duplicate update + tk.MustExec("insert into t (a) values ('abc') on duplicate key update a='bbc'") + tk.MustQuery("select a from t order by a").Check(testkit.Rows("acd", "bbb", "bbc")) + tk.MustQuery("select * from t where a = 'bbc'").Check(testkit.Rows("bbc b")) + // TODO: fix below test. + //tk.MustQuery("select a from t partition (p0) order by a").Check(testkit.Rows("acd")) + //tk.MustQuery("select a from t partition (p1) order by a").Check(testkit.Rows("bbb", "bbc")) + } +} + +func TestIssue20724(t *testing.T) { + collate.SetNewCollationEnabledForTest(true) + defer collate.SetNewCollationEnabledForTest(false) + + store, clean := testkit.CreateMockStore(t) + defer clean() + tk := testkit.NewTestKit(t, store) + tk.MustExec("use test") + tk.MustExec("drop table if exists t1") + tk.MustExec("create table t1(a varchar(10) collate utf8mb4_general_ci)") + tk.MustExec("insert into t1 values ('a')") + tk.MustExec("update t1 set a = 'A'") + tk.MustQuery("select * from t1").Check(testkit.Rows("A")) + tk.MustExec("drop table t1") +} + +func TestIssue20840(t *testing.T) { + collate.SetNewCollationEnabledForTest(true) + defer collate.SetNewCollationEnabledForTest(false) + + store, clean := testkit.CreateMockStore(t) + defer clean() + tk := testkit.NewTestKit(t, store) + tk.MustExec("use test") + tk.MustExec("drop table if exists t1") + tk.Session().GetSessionVars().EnableClusteredIndex = variable.ClusteredIndexDefModeIntOnly + tk.MustExec("create table t1 (i varchar(20) unique key) collate=utf8mb4_general_ci") + tk.MustExec("insert into t1 values ('a')") + tk.MustExec("replace into t1 values ('A')") + tk.MustQuery("select * from t1").Check(testkit.Rows("A")) + tk.MustExec("drop table t1") +} + +func TestIssueInsertPrefixIndexForNonUTF8Collation(t *testing.T) { + collate.SetNewCollationEnabledForTest(true) + defer collate.SetNewCollationEnabledForTest(false) + + store, clean := testkit.CreateMockStore(t) + defer clean() + tk := testkit.NewTestKit(t, store) + tk.MustExec("use test") + tk.MustExec("drop table if exists t1, t2, t3") + tk.MustExec("create table t1 ( c_int int, c_str varchar(40) character set ascii collate ascii_bin, primary key(c_int, c_str(8)) clustered , unique key(c_str))") + tk.MustExec("create table t2 ( c_int int, c_str varchar(40) character set latin1 collate latin1_bin, primary key(c_int, c_str(8)) clustered , unique key(c_str))") + tk.MustExec("insert into t1 values (3, 'fervent brattain')") + tk.MustExec("insert into t2 values (3, 'fervent brattain')") + tk.MustExec("admin check table t1") + tk.MustExec("admin check table t2") + + tk.MustExec("create table t3 (x varchar(40) CHARACTER SET ascii COLLATE ascii_bin, UNIQUE KEY uk(x(4)))") + tk.MustExec("insert into t3 select 'abc '") + tk.MustGetErrCode("insert into t3 select 'abc d'", 1062) +} diff --git a/executor/write_test.go b/executor/write_test.go index 5fe78511237da..879c8c76c035f 100644 --- a/executor/write_test.go +++ b/executor/write_test.go @@ -19,10 +19,8 @@ import ( "errors" "fmt" "strconv" - "sync" + "testing" - . "github.com/pingcap/check" - "github.com/pingcap/tidb/config" "github.com/pingcap/tidb/executor" "github.com/pingcap/tidb/kv" "github.com/pingcap/tidb/parser/model" @@ -31,93 +29,91 @@ import ( "github.com/pingcap/tidb/session" "github.com/pingcap/tidb/sessionctx" "github.com/pingcap/tidb/sessionctx/stmtctx" - "github.com/pingcap/tidb/sessionctx/variable" "github.com/pingcap/tidb/store/mockstore" "github.com/pingcap/tidb/table" "github.com/pingcap/tidb/table/tables" + "github.com/pingcap/tidb/testkit" "github.com/pingcap/tidb/types" - "github.com/pingcap/tidb/util/collate" + "github.com/pingcap/tidb/util" "github.com/pingcap/tidb/util/mock" - "github.com/pingcap/tidb/util/testkit" "github.com/pingcap/tidb/util/testutil" + "github.com/stretchr/testify/require" ) -type testBypassSuite struct{} - -func (s *testBypassSuite) SetUpSuite(c *C) { -} - -func (s *testSuite) TestInsert(c *C) { - tk := testkit.NewTestKit(c, s.store) +func TestInsert(t *testing.T) { + t.Parallel() + store, clean := testkit.CreateMockStore(t) + defer clean() + tk := testkit.NewTestKit(t, store) tk.MustExec("use test") testSQL := `drop table if exists insert_test;create table insert_test (id int PRIMARY KEY AUTO_INCREMENT, c1 int, c2 int, c3 int default 1);` tk.MustExec(testSQL) testSQL = `insert insert_test (c1) values (1),(2),(NULL);` tk.MustExec(testSQL) - tk.CheckLastMessage("Records: 3 Duplicates: 0 Warnings: 0") + require.Equal(t, tk.Session().LastMessage(), "Records: 3 Duplicates: 0 Warnings: 0") errInsertSelectSQL := `insert insert_test (c1) values ();` tk.MustExec("begin") _, err := tk.Exec(errInsertSelectSQL) - c.Assert(err, NotNil) + require.Error(t, err) tk.MustExec("rollback") errInsertSelectSQL = `insert insert_test (c1, c2) values (1,2),(1);` tk.MustExec("begin") _, err = tk.Exec(errInsertSelectSQL) - c.Assert(err, NotNil) + require.Error(t, err) tk.MustExec("rollback") errInsertSelectSQL = `insert insert_test (xxx) values (3);` tk.MustExec("begin") _, err = tk.Exec(errInsertSelectSQL) - c.Assert(err, NotNil) + require.Error(t, err) tk.MustExec("rollback") errInsertSelectSQL = `insert insert_test_xxx (c1) values ();` tk.MustExec("begin") _, err = tk.Exec(errInsertSelectSQL) - c.Assert(err, NotNil) + require.Error(t, err) tk.MustExec("rollback") insertSetSQL := `insert insert_test set c1 = 3;` tk.MustExec(insertSetSQL) - tk.CheckLastMessage("") + require.Empty(t, tk.Session().LastMessage()) errInsertSelectSQL = `insert insert_test set c1 = 4, c1 = 5;` tk.MustExec("begin") _, err = tk.Exec(errInsertSelectSQL) - c.Assert(err, NotNil) + require.Error(t, err) tk.MustExec("rollback") errInsertSelectSQL = `insert insert_test set xxx = 6;` tk.MustExec("begin") _, err = tk.Exec(errInsertSelectSQL) - c.Assert(err, NotNil) + require.Error(t, err) tk.MustExec("rollback") insertSelectSQL := `create table insert_test_1 (id int, c1 int);` tk.MustExec(insertSelectSQL) insertSelectSQL = `insert insert_test_1 select id, c1 from insert_test;` tk.MustExec(insertSelectSQL) - tk.CheckLastMessage("Records: 4 Duplicates: 0 Warnings: 0") + require.Equal(t, tk.Session().LastMessage(), "Records: 4 Duplicates: 0 Warnings: 0") insertSelectSQL = `create table insert_test_2 (id int, c1 int);` tk.MustExec(insertSelectSQL) insertSelectSQL = `insert insert_test_1 select id, c1 from insert_test union select id * 10, c1 * 10 from insert_test;` tk.MustExec(insertSelectSQL) - tk.CheckLastMessage("Records: 8 Duplicates: 0 Warnings: 0") + require.Equal(t, tk.Session().LastMessage(), "Records: 8 Duplicates: 0 Warnings: 0") errInsertSelectSQL = `insert insert_test_1 select c1 from insert_test;` tk.MustExec("begin") _, err = tk.Exec(errInsertSelectSQL) - c.Assert(err, NotNil) + require.Error(t, err) tk.MustExec("rollback") errInsertSelectSQL = `insert insert_test_1 values(default, default, default, default, default)` tk.MustExec("begin") _, err = tk.Exec(errInsertSelectSQL) - c.Assert(err, NotNil) + require.Error(t, err) tk.MustExec("rollback") // Updating column is PK handle. @@ -127,22 +123,22 @@ func (s *testSuite) TestInsert(c *C) { r.Check(testkit.Rows(rowStr)) insertSQL := `insert into insert_test (id, c3) values (1, 2) on duplicate key update id=values(id), c2=10;` tk.MustExec(insertSQL) - tk.CheckLastMessage("") + require.Empty(t, tk.Session().LastMessage()) r = tk.MustQuery("select * from insert_test where id = 1;") rowStr = fmt.Sprintf("%v %v %v %v", "1", "1", "10", "1") r.Check(testkit.Rows(rowStr)) insertSQL = `insert into insert_test (id, c2) values (1, 1) on duplicate key update insert_test.c2=10;` tk.MustExec(insertSQL) - tk.CheckLastMessage("") + require.Empty(t, tk.Session().LastMessage()) _, err = tk.Exec(`insert into insert_test (id, c2) values(1, 1) on duplicate key update t.c2 = 10`) - c.Assert(err, NotNil) + require.Error(t, err) // for on duplicate key insertSQL = `INSERT INTO insert_test (id, c3) VALUES (1, 2) ON DUPLICATE KEY UPDATE c3=values(c3)+c3+3;` tk.MustExec(insertSQL) - tk.CheckLastMessage("") + require.Empty(t, tk.Session().LastMessage()) r = tk.MustQuery("select * from insert_test where id = 1;") rowStr = fmt.Sprintf("%v %v %v %v", "1", "1", "10", "6") r.Check(testkit.Rows(rowStr)) @@ -150,21 +146,21 @@ func (s *testSuite) TestInsert(c *C) { // for on duplicate key with ignore insertSQL = `INSERT IGNORE INTO insert_test (id, c3) VALUES (1, 2) ON DUPLICATE KEY UPDATE c3=values(c3)+c3+3;` tk.MustExec(insertSQL) - tk.CheckLastMessage("") + require.Empty(t, tk.Session().LastMessage()) r = tk.MustQuery("select * from insert_test where id = 1;") rowStr = fmt.Sprintf("%v %v %v %v", "1", "1", "10", "11") r.Check(testkit.Rows(rowStr)) tk.MustExec("create table insert_err (id int, c1 varchar(8))") _, err = tk.Exec("insert insert_err values (1, 'abcdabcdabcd')") - c.Assert(types.ErrDataTooLong.Equal(err), IsTrue) + require.True(t, types.ErrDataTooLong.Equal(err)) _, err = tk.Exec("insert insert_err values (1, '你好,世界')") - c.Assert(err, IsNil) + require.NoError(t, err) tk.MustExec("create table TEST1 (ID INT NOT NULL, VALUE INT DEFAULT NULL, PRIMARY KEY (ID))") _, err = tk.Exec("INSERT INTO TEST1(id,value) VALUE(3,3) on DUPLICATE KEY UPDATE VALUE=4") - c.Assert(err, IsNil) - tk.CheckLastMessage("") + require.NoError(t, err) + require.Empty(t, tk.Session().LastMessage()) tk.MustExec("create table t (id int)") tk.MustExec("insert into t values(1)") @@ -176,21 +172,21 @@ func (s *testSuite) TestInsert(c *C) { tk.MustExec("drop table if exists t") tk.MustExec("create table t(c decimal(5, 5))") _, err = tk.Exec("insert into t value(0)") - c.Assert(err, IsNil) + require.NoError(t, err) _, err = tk.Exec("insert into t value(1)") - c.Assert(types.ErrWarnDataOutOfRange.Equal(err), IsTrue) + require.True(t, types.ErrWarnDataOutOfRange.Equal(err)) tk.MustExec("drop table if exists t") tk.MustExec("create table t(c binary(255))") _, err = tk.Exec("insert into t value(1)") - c.Assert(err, IsNil) + require.NoError(t, err) r = tk.MustQuery("select length(c) from t;") r.Check(testkit.Rows("255")) tk.MustExec("drop table if exists t") tk.MustExec("create table t(c varbinary(255))") _, err = tk.Exec("insert into t value(1)") - c.Assert(err, IsNil) + require.NoError(t, err) r = tk.MustQuery("select length(c) from t;") r.Check(testkit.Rows("1")) @@ -200,7 +196,7 @@ func (s *testSuite) TestInsert(c *C) { tk.MustExec("set @origin_time_zone = @@time_zone") tk.MustExec("set @@time_zone = '+08:00'") _, err = tk.Exec("insert into t value(Unix_timestamp('2002-10-27 01:00'))") - c.Assert(err, IsNil) + require.NoError(t, err) r = tk.MustQuery("select * from t;") r.Check(testkit.Rows("1035651600")) tk.MustExec("set @@time_zone = @origin_time_zone") @@ -208,10 +204,9 @@ func (s *testSuite) TestInsert(c *C) { // issue 3832 tk.MustExec("create table t1 (b char(0));") _, err = tk.Exec(`insert into t1 values ("");`) - c.Assert(err, IsNil) + require.NoError(t, err) // issue 3895 - tk = testkit.NewTestKit(c, s.store) tk.MustExec("USE test;") tk.MustExec("DROP TABLE IF EXISTS t;") tk.MustExec("CREATE TABLE t(a DECIMAL(4,2));") @@ -226,7 +221,7 @@ func (s *testSuite) TestInsert(c *C) { tk.MustExec("DROP TABLE IF EXISTS t;") tk.MustExec("CREATE TABLE t(a datetime);") _, err = tk.Exec("INSERT INTO t VALUES('2017-00-00')") - c.Assert(err, NotNil) + require.Error(t, err) tk.MustExec("set sql_mode = ''") tk.MustExec("INSERT INTO t VALUES('2017-00-00')") r = tk.MustQuery("SELECT * FROM t;") @@ -251,7 +246,7 @@ func (s *testSuite) TestInsert(c *C) { tk.MustExec("create table t(a bigint unsigned);") tk.MustExec(" set @orig_sql_mode = @@sql_mode; set @@sql_mode = 'strict_all_tables';") _, err = tk.Exec("insert into t value (-1);") - c.Assert(types.ErrWarnDataOutOfRange.Equal(err), IsTrue) + require.True(t, types.ErrWarnDataOutOfRange.Equal(err)) tk.MustExec("set @@sql_mode = '';") tk.MustExec("insert into t value (-1);") // TODO: the following warning messages are not consistent with MySQL, fix them in the future PRs @@ -278,7 +273,7 @@ func (s *testSuite) TestInsert(c *C) { tk.MustExec("insert into t value(20070219173709.055870), (20070219173709.055), (20070219173709.055870123)") tk.MustQuery("select * from t").Check(testkit.Rows("17:37:09.055870", "17:37:09.055000", "17:37:09.055870")) _, err = tk.Exec("insert into t value(-20070219173709.055870)") - c.Assert(err.Error(), Equals, "[table:1292]Incorrect time value: '-20070219173709.055870' for column 'a' at row 1") + require.EqualError(t, err, "[table:1292]Incorrect time value: '-20070219173709.055870' for column 'a' at row 1") tk.MustExec("drop table if exists t") tk.MustExec("set @@sql_mode=''") @@ -306,16 +301,16 @@ func (s *testSuite) TestInsert(c *C) { tk.MustExec("create view v as select * from t") _, err = tk.Exec("insert into v values(1,2)") - c.Assert(err.Error(), Equals, "insert into view v is not supported now.") + require.EqualError(t, err, "insert into view v is not supported now.") _, err = tk.Exec("replace into v values(1,2)") - c.Assert(err.Error(), Equals, "replace into view v is not supported now.") + require.EqualError(t, err, "replace into view v is not supported now.") tk.MustExec("drop view v") tk.MustExec("create sequence seq") _, err = tk.Exec("insert into seq values()") - c.Assert(err.Error(), Equals, "insert into sequence seq is not supported now.") + require.EqualError(t, err, "insert into sequence seq is not supported now.") _, err = tk.Exec("replace into seq values()") - c.Assert(err.Error(), Equals, "replace into sequence seq is not supported now.") + require.EqualError(t, err, "replace into sequence seq is not supported now.") tk.MustExec("drop sequence seq") // issue 22851 @@ -323,14 +318,17 @@ func (s *testSuite) TestInsert(c *C) { tk.MustExec("create table t(name varchar(255), b int, c int, primary key(name(2)))") tk.MustExec("insert into t(name, b) values(\"cha\", 3)") _, err = tk.Exec("insert into t(name, b) values(\"chb\", 3)") - c.Assert(err.Error(), Equals, "[kv:1062]Duplicate entry 'ch' for key 'PRIMARY'") + require.EqualError(t, err, "[kv:1062]Duplicate entry 'ch' for key 'PRIMARY'") tk.MustExec("insert into t(name, b) values(\"测试\", 3)") _, err = tk.Exec("insert into t(name, b) values(\"测试\", 3)") - c.Assert(err.Error(), Equals, "[kv:1062]Duplicate entry '测试' for key 'PRIMARY'") + require.EqualError(t, err, "[kv:1062]Duplicate entry '测试' for key 'PRIMARY'") } -func (s *testSuiteP2) TestMultiBatch(c *C) { - tk := testkit.NewTestKit(c, s.store) +func TestMultiBatch(t *testing.T) { + t.Parallel() + store, clean := testkit.CreateMockStore(t) + defer clean() + tk := testkit.NewTestKit(t, store) tk.MustExec("use test") tk.MustExec("drop table if exists t,t0") tk.MustExec("create table t0 (i int)") @@ -341,8 +339,11 @@ func (s *testSuiteP2) TestMultiBatch(c *C) { tk.MustExec("admin check table t") } -func (s *testSuite4) TestInsertAutoInc(c *C) { - tk := testkit.NewTestKit(c, s.store) +func TestInsertAutoInc(t *testing.T) { + t.Parallel() + store, clean := testkit.CreateMockStore(t) + defer clean() + tk := testkit.NewTestKit(t, store) tk.MustExec("use test") createSQL := `drop table if exists insert_autoinc_test; create table insert_autoinc_test (id int primary key auto_increment, c1 int);` tk.MustExec(createSQL) @@ -450,7 +451,7 @@ func (s *testSuite4) TestInsertAutoInc(c *C) { insertSQL = `insert into insert_autoinc_test(id, c1) values (0, 5)` _, err := tk.Exec(insertSQL) // ERROR 1062 (23000): Duplicate entry '0' for key 'PRIMARY' - c.Assert(err, NotNil) + require.Error(t, err) insertSQL = `insert into insert_autoinc_test(c1) values (6)` tk.MustExec(insertSQL) r = tk.MustQuery("select * from insert_autoinc_test;") @@ -474,36 +475,39 @@ func (s *testSuite4) TestInsertAutoInc(c *C) { r.Check(testkit.Rows(rowStr4, rowStr1, rowStr2, rowStr3, rowStr5, rowStr6, rowStr7, rowStr8)) } -func (s *testSuite4) TestInsertIgnore(c *C) { +func TestInsertIgnore(t *testing.T) { + t.Parallel() + store, clean := testkit.CreateMockStore(t) + defer clean() var cfg kv.InjectionConfig - tk := testkit.NewTestKit(c, kv.NewInjectedStore(s.store, &cfg)) + tk := testkit.NewTestKit(t, kv.NewInjectedStore(store, &cfg)) tk.MustExec("use test") testSQL := `drop table if exists t; create table t (id int PRIMARY KEY AUTO_INCREMENT, c1 int unique key);` tk.MustExec(testSQL) testSQL = `insert into t values (1, 2);` tk.MustExec(testSQL) - tk.CheckLastMessage("") + require.Empty(t, tk.Session().LastMessage()) r := tk.MustQuery("select * from t;") rowStr := fmt.Sprintf("%v %v", "1", "2") r.Check(testkit.Rows(rowStr)) tk.MustExec("insert ignore into t values (1, 3), (2, 3)") - tk.CheckLastMessage("Records: 2 Duplicates: 1 Warnings: 1") + require.Equal(t, tk.Session().LastMessage(), "Records: 2 Duplicates: 1 Warnings: 1") r = tk.MustQuery("select * from t;") rowStr1 := fmt.Sprintf("%v %v", "2", "3") r.Check(testkit.Rows(rowStr, rowStr1)) tk.MustExec("insert ignore into t values (3, 4), (3, 4)") - tk.CheckLastMessage("Records: 2 Duplicates: 1 Warnings: 1") + require.Equal(t, tk.Session().LastMessage(), "Records: 2 Duplicates: 1 Warnings: 1") r = tk.MustQuery("select * from t;") rowStr2 := fmt.Sprintf("%v %v", "3", "4") r.Check(testkit.Rows(rowStr, rowStr1, rowStr2)) tk.MustExec("begin") tk.MustExec("insert ignore into t values (4, 4), (4, 5), (4, 6)") - tk.CheckLastMessage("Records: 3 Duplicates: 2 Warnings: 2") + require.Equal(t, tk.Session().LastMessage(), "Records: 3 Duplicates: 2 Warnings: 2") r = tk.MustQuery("select * from t;") rowStr3 := fmt.Sprintf("%v %v", "4", "5") r.Check(testkit.Rows(rowStr, rowStr1, rowStr2, rowStr3)) @@ -511,7 +515,7 @@ func (s *testSuite4) TestInsertIgnore(c *C) { cfg.SetGetError(errors.New("foo")) _, err := tk.Exec("insert ignore into t values (1, 3)") - c.Assert(err, NotNil) + require.Error(t, err) cfg.SetGetError(nil) // for issue 4268 @@ -520,14 +524,14 @@ func (s *testSuite4) TestInsertIgnore(c *C) { tk.MustExec(testSQL) testSQL = "insert ignore into t select '1a';" _, err = tk.Exec(testSQL) - c.Assert(err, IsNil) - tk.CheckLastMessage("Records: 1 Duplicates: 0 Warnings: 1") + require.NoError(t, err) + require.Equal(t, tk.Session().LastMessage(), "Records: 1 Duplicates: 0 Warnings: 1") r = tk.MustQuery("SHOW WARNINGS") r.Check(testkit.Rows("Warning 1292 Truncated incorrect DOUBLE value: '1a'")) testSQL = "insert ignore into t values ('1a')" _, err = tk.Exec(testSQL) - c.Assert(err, IsNil) - tk.CheckLastMessage("") + require.NoError(t, err) + require.Empty(t, tk.Session().LastMessage()) r = tk.MustQuery("SHOW WARNINGS") r.Check(testkit.Rows("Warning 1292 Truncated incorrect DOUBLE value: '1a'")) @@ -537,10 +541,10 @@ func (s *testSuite4) TestInsertIgnore(c *C) { tk.MustExec(testSQL) testSQL = "insert ignore into t values (1,1);" tk.MustExec(testSQL) - tk.CheckLastMessage("") + require.Empty(t, tk.Session().LastMessage()) _, err = tk.Exec(testSQL) - tk.CheckLastMessage("") - c.Assert(err, IsNil) + require.Empty(t, tk.Session().LastMessage()) + require.NoError(t, err) r = tk.MustQuery("SHOW WARNINGS") r.Check(testkit.Rows("Warning 1062 Duplicate entry '1' for key 'PRIMARY'")) @@ -582,7 +586,7 @@ commit;` tk.MustExec(testSQL) testSQL = `insert ignore into badnull values (null)` tk.MustExec(testSQL) - tk.CheckLastMessage("") + require.Empty(t, tk.Session().LastMessage()) tk.MustQuery("show warnings").Check(testkit.Rows("Warning 1048 Column 'i' cannot be null")) testSQL = `select * from badnull` tk.MustQuery(testSQL).Check(testkit.Rows("0")) @@ -592,16 +596,19 @@ commit;` tk.MustQuery("show warnings").Check(testkit.Rows("Warning 1526 Table has no partition for value 3")) } -func (s *testSuite8) TestInsertOnDup(c *C) { +func TestInsertOnDup(t *testing.T) { + t.Parallel() + store, clean := testkit.CreateMockStore(t) + defer clean() var cfg kv.InjectionConfig - tk := testkit.NewTestKit(c, kv.NewInjectedStore(s.store, &cfg)) + tk := testkit.NewTestKit(t, kv.NewInjectedStore(store, &cfg)) tk.MustExec("use test") testSQL := `drop table if exists t; create table t (i int unique key);` tk.MustExec(testSQL) testSQL = `insert into t values (1),(2);` tk.MustExec(testSQL) - tk.CheckLastMessage("Records: 2 Duplicates: 0 Warnings: 0") + require.Equal(t, tk.Session().LastMessage(), "Records: 2 Duplicates: 0 Warnings: 0") r := tk.MustQuery("select * from t;") rowStr1 := fmt.Sprintf("%v", "1") @@ -609,12 +616,12 @@ func (s *testSuite8) TestInsertOnDup(c *C) { r.Check(testkit.Rows(rowStr1, rowStr2)) tk.MustExec("insert into t values (1), (2) on duplicate key update i = values(i)") - tk.CheckLastMessage("Records: 2 Duplicates: 0 Warnings: 0") + require.Equal(t, tk.Session().LastMessage(), "Records: 2 Duplicates: 0 Warnings: 0") r = tk.MustQuery("select * from t;") r.Check(testkit.Rows(rowStr1, rowStr2)) tk.MustExec("insert into t values (2), (3) on duplicate key update i = 3") - tk.CheckLastMessage("Records: 2 Duplicates: 1 Warnings: 0") + require.Equal(t, tk.Session().LastMessage(), "Records: 2 Duplicates: 1 Warnings: 0") r = tk.MustQuery("select * from t;") rowStr3 := fmt.Sprintf("%v", "3") r.Check(testkit.Rows(rowStr1, rowStr3)) @@ -624,14 +631,14 @@ func (s *testSuite8) TestInsertOnDup(c *C) { tk.MustExec(testSQL) testSQL = `insert into t values (-1, 1);` tk.MustExec(testSQL) - tk.CheckLastMessage("") + require.Empty(t, tk.Session().LastMessage()) r = tk.MustQuery("select * from t;") rowStr1 = fmt.Sprintf("%v %v", "-1", "1") r.Check(testkit.Rows(rowStr1)) tk.MustExec("insert into t values (1, 1) on duplicate key update j = values(j)") - tk.CheckLastMessage("") + require.Empty(t, tk.Session().LastMessage()) r = tk.MustQuery("select * from t;") r.Check(testkit.Rows(rowStr1)) @@ -696,13 +703,13 @@ commit;` f2 VARCHAR(5) NOT NULL UNIQUE); INSERT t1 (f2) VALUES ('test') ON DUPLICATE KEY UPDATE f1 = LAST_INSERT_ID(f1);` tk.MustExec(testSQL) - tk.CheckLastMessage("") + require.Empty(t, tk.Session().LastMessage()) testSQL = `SELECT LAST_INSERT_ID();` r = tk.MustQuery(testSQL) r.Check(testkit.Rows("1")) testSQL = `INSERT t1 (f2) VALUES ('test') ON DUPLICATE KEY UPDATE f1 = LAST_INSERT_ID(f1);` tk.MustExec(testSQL) - tk.CheckLastMessage("") + require.Empty(t, tk.Session().LastMessage()) testSQL = `SELECT LAST_INSERT_ID();` r = tk.MustQuery(testSQL) r.Check(testkit.Rows("1")) @@ -712,19 +719,19 @@ commit;` f2 VARCHAR(5) NOT NULL UNIQUE); INSERT t1 (f2) VALUES ('test') ON DUPLICATE KEY UPDATE f1 = LAST_INSERT_ID(f1);` tk.MustExec(testSQL) - tk.CheckLastMessage("") + require.Empty(t, tk.Session().LastMessage()) testSQL = `SELECT LAST_INSERT_ID();` r = tk.MustQuery(testSQL) r.Check(testkit.Rows("1")) testSQL = `INSERT t1 (f2) VALUES ('test') ON DUPLICATE KEY UPDATE f1 = LAST_INSERT_ID(f1);` tk.MustExec(testSQL) - tk.CheckLastMessage("") + require.Empty(t, tk.Session().LastMessage()) testSQL = `SELECT LAST_INSERT_ID();` r = tk.MustQuery(testSQL) r.Check(testkit.Rows("1")) testSQL = `INSERT t1 (f2) VALUES ('test') ON DUPLICATE KEY UPDATE f1 = 2;` tk.MustExec(testSQL) - tk.CheckLastMessage("") + require.Empty(t, tk.Session().LastMessage()) testSQL = `SELECT LAST_INSERT_ID();` r = tk.MustQuery(testSQL) r.Check(testkit.Rows("1")) @@ -733,21 +740,21 @@ commit;` CREATE TABLE t1 (f1 INT); INSERT t1 VALUES (1) ON DUPLICATE KEY UPDATE f1 = 1;` tk.MustExec(testSQL) - tk.CheckLastMessage("") + require.Empty(t, tk.Session().LastMessage()) tk.MustQuery(`SELECT * FROM t1;`).Check(testkit.Rows("1")) testSQL = `DROP TABLE IF EXISTS t1; CREATE TABLE t1 (f1 INT PRIMARY KEY, f2 INT NOT NULL UNIQUE); INSERT t1 VALUES (1, 1);` tk.MustExec(testSQL) - tk.CheckLastMessage("") + require.Empty(t, tk.Session().LastMessage()) tk.MustExec(`INSERT t1 VALUES (1, 1), (1, 1) ON DUPLICATE KEY UPDATE f1 = 2, f2 = 2;`) - tk.CheckLastMessage("Records: 2 Duplicates: 1 Warnings: 0") + require.Equal(t, tk.Session().LastMessage(), "Records: 2 Duplicates: 1 Warnings: 0") tk.MustQuery(`SELECT * FROM t1 order by f1;`).Check(testkit.Rows("1 1", "2 2")) _, err := tk.Exec(`INSERT t1 VALUES (1, 1) ON DUPLICATE KEY UPDATE f2 = null;`) - c.Assert(err, NotNil) + require.Error(t, err) tk.MustExec(`INSERT IGNORE t1 VALUES (1, 1) ON DUPLICATE KEY UPDATE f2 = null;`) - tk.CheckLastMessage("") + require.Empty(t, tk.Session().LastMessage()) tk.MustQuery("show warnings").Check(testkit.Rows("Warning 1048 Column 'f2' cannot be null")) tk.MustQuery(`SELECT * FROM t1 order by f1;`).Check(testkit.Rows("1 0", "2 2")) @@ -757,24 +764,27 @@ commit;` tk.MustQuery(`SELECT * FROM t1 order by f1;`).Check(testkit.Rows("1 0", "2 2")) } -func (s *testSuite4) TestInsertIgnoreOnDup(c *C) { - tk := testkit.NewTestKit(c, s.store) +func TestInsertIgnoreOnDup(t *testing.T) { + t.Parallel() + store, clean := testkit.CreateMockStore(t) + defer clean() + tk := testkit.NewTestKit(t, store) tk.MustExec("use test") testSQL := `drop table if exists t; create table t (i int not null primary key, j int unique key);` tk.MustExec(testSQL) testSQL = `insert into t values (1, 1), (2, 2);` tk.MustExec(testSQL) - tk.CheckLastMessage("Records: 2 Duplicates: 0 Warnings: 0") + require.Equal(t, tk.Session().LastMessage(), "Records: 2 Duplicates: 0 Warnings: 0") testSQL = `insert ignore into t values(1, 1) on duplicate key update i = 2;` tk.MustExec(testSQL) - tk.CheckLastMessage("") + require.Empty(t, tk.Session().LastMessage()) testSQL = `select * from t;` r := tk.MustQuery(testSQL) r.Check(testkit.Rows("1 1", "2 2")) testSQL = `insert ignore into t values(1, 1) on duplicate key update j = 2;` tk.MustExec(testSQL) - tk.CheckLastMessage("") + require.Empty(t, tk.Session().LastMessage()) testSQL = `select * from t;` r = tk.MustQuery(testSQL) r.Check(testkit.Rows("1 1", "2 2")) @@ -809,8 +819,11 @@ func (s *testSuite4) TestInsertIgnoreOnDup(c *C) { tk.MustQuery("select * from t6").Check(testkit.Rows("100 10 1000")) } -func (s *testSuite4) TestInsertSetWithDefault(c *C) { - tk := testkit.NewTestKit(c, s.store) +func TestInsertSetWithDefault(t *testing.T) { + t.Parallel() + store, clean := testkit.CreateMockStore(t) + defer clean() + tk := testkit.NewTestKit(t, store) tk.MustExec("use test") // Assign `DEFAULT` in `INSERT ... SET ...` statement tk.MustExec("drop table if exists t1, t2;") @@ -856,8 +869,11 @@ func (s *testSuite4) TestInsertSetWithDefault(c *C) { tk.MustExec("drop table t1, t2") } -func (s *testSuite4) TestInsertOnDupUpdateDefault(c *C) { - tk := testkit.NewTestKit(c, s.store) +func TestInsertOnDupUpdateDefault(t *testing.T) { + t.Parallel() + store, clean := testkit.CreateMockStore(t) + defer clean() + tk := testkit.NewTestKit(t, store) tk.MustExec("use test") // Assign `DEFAULT` in `INSERT ... ON DUPLICATE KEY UPDATE ...` statement tk.MustExec("drop table if exists t1, t2;") @@ -895,78 +911,81 @@ func (s *testSuite4) TestInsertOnDupUpdateDefault(c *C) { tk.MustExec("insert into t values (22, 'gold witch'), (24, 'gray singer'), (21, 'silver sight');") tk.MustExec("begin;") err := tk.ExecToErr("insert into t values (21,'black warlock'), (22, 'dark sloth'), (21, 'cyan song') on duplicate key update c_int = c_int + 1, c_string = concat(c_int, ':', c_string);") - c.Assert(kv.ErrKeyExists.Equal(err), IsTrue) + require.True(t, kv.ErrKeyExists.Equal(err)) tk.MustExec("commit;") tk.MustQuery("select * from t order by c_int;").Check(testutil.RowsWithSep("|", "21|silver sight", "22|gold witch", "24|gray singer")) tk.MustExec("drop table t;") } -func (s *testSuite4) TestReplace(c *C) { - tk := testkit.NewTestKit(c, s.store) +func TestReplace(t *testing.T) { + t.Parallel() + store, clean := testkit.CreateMockStore(t) + defer clean() + tk := testkit.NewTestKit(t, store) tk.MustExec("use test") testSQL := `drop table if exists replace_test; create table replace_test (id int PRIMARY KEY AUTO_INCREMENT, c1 int, c2 int, c3 int default 1);` tk.MustExec(testSQL) testSQL = `replace replace_test (c1) values (1),(2),(NULL);` tk.MustExec(testSQL) - tk.CheckLastMessage("Records: 3 Duplicates: 0 Warnings: 0") + require.Equal(t, tk.Session().LastMessage(), "Records: 3 Duplicates: 0 Warnings: 0") errReplaceSQL := `replace replace_test (c1) values ();` tk.MustExec("begin") _, err := tk.Exec(errReplaceSQL) - c.Assert(err, NotNil) + require.Error(t, err) tk.MustExec("rollback") errReplaceSQL = `replace replace_test (c1, c2) values (1,2),(1);` tk.MustExec("begin") _, err = tk.Exec(errReplaceSQL) - c.Assert(err, NotNil) + require.Error(t, err) tk.MustExec("rollback") errReplaceSQL = `replace replace_test (xxx) values (3);` tk.MustExec("begin") _, err = tk.Exec(errReplaceSQL) - c.Assert(err, NotNil) + require.Error(t, err) tk.MustExec("rollback") errReplaceSQL = `replace replace_test_xxx (c1) values ();` tk.MustExec("begin") _, err = tk.Exec(errReplaceSQL) - c.Assert(err, NotNil) + require.Error(t, err) tk.MustExec("rollback") replaceSetSQL := `replace replace_test set c1 = 3;` tk.MustExec(replaceSetSQL) - tk.CheckLastMessage("") + require.Empty(t, tk.Session().LastMessage()) errReplaceSetSQL := `replace replace_test set c1 = 4, c1 = 5;` tk.MustExec("begin") _, err = tk.Exec(errReplaceSetSQL) - c.Assert(err, NotNil) + require.Error(t, err) tk.MustExec("rollback") errReplaceSetSQL = `replace replace_test set xxx = 6;` tk.MustExec("begin") _, err = tk.Exec(errReplaceSetSQL) - c.Assert(err, NotNil) + require.Error(t, err) tk.MustExec("rollback") replaceSelectSQL := `create table replace_test_1 (id int, c1 int);` tk.MustExec(replaceSelectSQL) replaceSelectSQL = `replace replace_test_1 select id, c1 from replace_test;` tk.MustExec(replaceSelectSQL) - tk.CheckLastMessage("Records: 4 Duplicates: 0 Warnings: 0") + require.Equal(t, tk.Session().LastMessage(), "Records: 4 Duplicates: 0 Warnings: 0") replaceSelectSQL = `create table replace_test_2 (id int, c1 int);` tk.MustExec(replaceSelectSQL) replaceSelectSQL = `replace replace_test_1 select id, c1 from replace_test union select id * 10, c1 * 10 from replace_test;` tk.MustExec(replaceSelectSQL) - tk.CheckLastMessage("Records: 8 Duplicates: 0 Warnings: 0") + require.Equal(t, tk.Session().LastMessage(), "Records: 8 Duplicates: 0 Warnings: 0") errReplaceSelectSQL := `replace replace_test_1 select c1 from replace_test;` tk.MustExec("begin") _, err = tk.Exec(errReplaceSelectSQL) - c.Assert(err, NotNil) + require.Error(t, err) tk.MustExec("rollback") replaceUniqueIndexSQL := `create table replace_test_3 (c1 int, c2 int, UNIQUE INDEX (c2));` @@ -975,20 +994,20 @@ func (s *testSuite4) TestReplace(c *C) { tk.MustExec(replaceUniqueIndexSQL) replaceUniqueIndexSQL = `replace into replace_test_3 set c2=1;` tk.MustExec(replaceUniqueIndexSQL) - c.Assert(int64(tk.Se.AffectedRows()), Equals, int64(1)) - tk.CheckLastMessage("") + require.Equal(t, int64(1), int64(tk.Session().AffectedRows())) + require.Empty(t, tk.Session().LastMessage()) replaceUniqueIndexSQL = `replace into replace_test_3 set c1=1, c2=1;` tk.MustExec(replaceUniqueIndexSQL) - c.Assert(int64(tk.Se.AffectedRows()), Equals, int64(2)) - tk.CheckLastMessage("") + require.Equal(t, int64(2), int64(tk.Session().AffectedRows())) + require.Empty(t, tk.Session().LastMessage()) replaceUniqueIndexSQL = `replace into replace_test_3 set c2=NULL;` tk.MustExec(replaceUniqueIndexSQL) replaceUniqueIndexSQL = `replace into replace_test_3 set c2=NULL;` tk.MustExec(replaceUniqueIndexSQL) - c.Assert(int64(tk.Se.AffectedRows()), Equals, int64(1)) - tk.CheckLastMessage("") + require.Equal(t, int64(1), int64(tk.Session().AffectedRows())) + require.Empty(t, tk.Session().LastMessage()) replaceUniqueIndexSQL = `create table replace_test_4 (c1 int, c2 int, c3 int, UNIQUE INDEX (c1, c2));` tk.MustExec(replaceUniqueIndexSQL) @@ -996,8 +1015,8 @@ func (s *testSuite4) TestReplace(c *C) { tk.MustExec(replaceUniqueIndexSQL) replaceUniqueIndexSQL = `replace into replace_test_4 set c2=NULL;` tk.MustExec(replaceUniqueIndexSQL) - c.Assert(int64(tk.Se.AffectedRows()), Equals, int64(1)) - tk.CheckLastMessage("") + require.Equal(t, int64(1), int64(tk.Session().AffectedRows())) + require.Empty(t, tk.Session().LastMessage()) replacePrimaryKeySQL := `create table replace_test_5 (c1 int, c2 int, c3 int, PRIMARY KEY (c1, c2));` tk.MustExec(replacePrimaryKeySQL) @@ -1005,18 +1024,18 @@ func (s *testSuite4) TestReplace(c *C) { tk.MustExec(replacePrimaryKeySQL) replacePrimaryKeySQL = `replace into replace_test_5 set c1=1, c2=2;` tk.MustExec(replacePrimaryKeySQL) - c.Assert(int64(tk.Se.AffectedRows()), Equals, int64(1)) - tk.CheckLastMessage("") + require.Equal(t, int64(1), int64(tk.Session().AffectedRows())) + require.Empty(t, tk.Session().LastMessage()) // For Issue989 issue989SQL := `CREATE TABLE tIssue989 (a int, b int, PRIMARY KEY(a), UNIQUE KEY(b));` tk.MustExec(issue989SQL) issue989SQL = `insert into tIssue989 (a, b) values (1, 2);` tk.MustExec(issue989SQL) - tk.CheckLastMessage("") + require.Empty(t, tk.Session().LastMessage()) issue989SQL = `replace into tIssue989(a, b) values (111, 2);` tk.MustExec(issue989SQL) - tk.CheckLastMessage("") + require.Empty(t, tk.Session().LastMessage()) r := tk.MustQuery("select * from tIssue989;") r.Check(testkit.Rows("111 2")) @@ -1029,8 +1048,8 @@ func (s *testSuite4) TestReplace(c *C) { tk.MustExec(issue1012SQL) issue1012SQL = `replace into tIssue1012(a, b) values (1, 1);` tk.MustExec(issue1012SQL) - c.Assert(int64(tk.Se.AffectedRows()), Equals, int64(3)) - tk.CheckLastMessage("") + require.Equal(t, int64(3), int64(tk.Session().AffectedRows())) + require.Empty(t, tk.Session().LastMessage()) r = tk.MustQuery("select * from tIssue1012;") r.Check(testkit.Rows("1 1")) @@ -1039,17 +1058,17 @@ func (s *testSuite4) TestReplace(c *C) { tk.MustExec(`create table t1(a int primary key, b int);`) tk.MustExec(`insert into t1 values(1,1),(2,2),(3,3),(4,4),(5,5);`) tk.MustExec(`replace into t1 values(1,1);`) - c.Assert(int64(tk.Se.AffectedRows()), Equals, int64(1)) - tk.CheckLastMessage("") + require.Equal(t, int64(1), int64(tk.Session().AffectedRows())) + require.Empty(t, tk.Session().LastMessage()) tk.MustExec(`replace into t1 values(1,1),(2,2);`) - c.Assert(int64(tk.Se.AffectedRows()), Equals, int64(2)) - tk.CheckLastMessage("Records: 2 Duplicates: 0 Warnings: 0") + require.Equal(t, int64(2), int64(tk.Session().AffectedRows())) + require.Equal(t, tk.Session().LastMessage(), "Records: 2 Duplicates: 0 Warnings: 0") tk.MustExec(`replace into t1 values(4,14),(5,15),(6,16),(7,17),(8,18)`) - c.Assert(int64(tk.Se.AffectedRows()), Equals, int64(7)) - tk.CheckLastMessage("Records: 5 Duplicates: 2 Warnings: 0") + require.Equal(t, int64(7), int64(tk.Session().AffectedRows())) + require.Equal(t, tk.Session().LastMessage(), "Records: 5 Duplicates: 2 Warnings: 0") tk.MustExec(`replace into t1 select * from (select 1, 2) as tmp;`) - c.Assert(int64(tk.Se.AffectedRows()), Equals, int64(2)) - tk.CheckLastMessage("Records: 1 Duplicates: 1 Warnings: 0") + require.Equal(t, int64(2), int64(tk.Session().AffectedRows())) + require.Equal(t, tk.Session().LastMessage(), "Records: 1 Duplicates: 1 Warnings: 0") // Assign `DEFAULT` in `REPLACE` statement tk.MustExec("drop table if exists t1, t2;") @@ -1082,8 +1101,11 @@ func (s *testSuite4) TestReplace(c *C) { tk.MustExec("drop table t1, t2") } -func (s *testSuite2) TestGeneratedColumnForInsert(c *C) { - tk := testkit.NewTestKit(c, s.store) +func TestGeneratedColumnForInsert(t *testing.T) { + t.Parallel() + store, clean := testkit.CreateMockStore(t) + defer clean() + tk := testkit.NewTestKit(t, store) tk.MustExec("use test") // test cases for default behavior @@ -1131,8 +1153,11 @@ func (s *testSuite2) TestGeneratedColumnForInsert(c *C) { tk.MustQuery(`select * from t1`).Check(testkit.Rows("1000 9.9")) } -func (s *testSuite4) TestPartitionedTableReplace(c *C) { - tk := testkit.NewTestKit(c, s.store) +func TestPartitionedTableReplace(t *testing.T) { + t.Parallel() + store, clean := testkit.CreateMockStore(t) + defer clean() + tk := testkit.NewTestKit(t, store) tk.MustExec("use test") testSQL := `drop table if exists replace_test; create table replace_test (id int PRIMARY KEY AUTO_INCREMENT, c1 int, c2 int, c3 int default 1) @@ -1144,46 +1169,46 @@ func (s *testSuite4) TestPartitionedTableReplace(c *C) { tk.MustExec(testSQL) testSQL = `replace replace_test (c1) values (1),(2),(NULL);` tk.MustExec(testSQL) - tk.CheckLastMessage("Records: 3 Duplicates: 0 Warnings: 0") + require.Equal(t, tk.Session().LastMessage(), "Records: 3 Duplicates: 0 Warnings: 0") errReplaceSQL := `replace replace_test (c1) values ();` tk.MustExec("begin") _, err := tk.Exec(errReplaceSQL) - c.Assert(err, NotNil) + require.Error(t, err) tk.MustExec("rollback") errReplaceSQL = `replace replace_test (c1, c2) values (1,2),(1);` tk.MustExec("begin") _, err = tk.Exec(errReplaceSQL) - c.Assert(err, NotNil) + require.Error(t, err) tk.MustExec("rollback") errReplaceSQL = `replace replace_test (xxx) values (3);` tk.MustExec("begin") _, err = tk.Exec(errReplaceSQL) - c.Assert(err, NotNil) + require.Error(t, err) tk.MustExec("rollback") errReplaceSQL = `replace replace_test_xxx (c1) values ();` tk.MustExec("begin") _, err = tk.Exec(errReplaceSQL) - c.Assert(err, NotNil) + require.Error(t, err) tk.MustExec("rollback") replaceSetSQL := `replace replace_test set c1 = 3;` tk.MustExec(replaceSetSQL) - tk.CheckLastMessage("") + require.Empty(t, tk.Session().LastMessage()) errReplaceSetSQL := `replace replace_test set c1 = 4, c1 = 5;` tk.MustExec("begin") _, err = tk.Exec(errReplaceSetSQL) - c.Assert(err, NotNil) + require.Error(t, err) tk.MustExec("rollback") errReplaceSetSQL = `replace replace_test set xxx = 6;` tk.MustExec("begin") _, err = tk.Exec(errReplaceSetSQL) - c.Assert(err, NotNil) + require.Error(t, err) tk.MustExec("rollback") tk.MustExec(`drop table if exists replace_test_1`) @@ -1194,7 +1219,7 @@ func (s *testSuite4) TestPartitionedTableReplace(c *C) { PARTITION p3 VALUES LESS THAN (10), PARTITION p4 VALUES LESS THAN (100))`) tk.MustExec(`replace replace_test_1 select id, c1 from replace_test;`) - tk.CheckLastMessage("Records: 4 Duplicates: 0 Warnings: 0") + require.Equal(t, tk.Session().LastMessage(), "Records: 4 Duplicates: 0 Warnings: 0") tk.MustExec(`drop table if exists replace_test_2`) tk.MustExec(`create table replace_test_2 (id int, c1 int) partition by range (id) ( @@ -1203,12 +1228,12 @@ func (s *testSuite4) TestPartitionedTableReplace(c *C) { PARTITION p2 VALUES LESS THAN (100), PARTITION p3 VALUES LESS THAN (300))`) tk.MustExec(`replace replace_test_1 select id, c1 from replace_test union select id * 10, c1 * 10 from replace_test;`) - tk.CheckLastMessage("Records: 8 Duplicates: 0 Warnings: 0") + require.Equal(t, tk.Session().LastMessage(), "Records: 8 Duplicates: 0 Warnings: 0") errReplaceSelectSQL := `replace replace_test_1 select c1 from replace_test;` tk.MustExec("begin") _, err = tk.Exec(errReplaceSelectSQL) - c.Assert(err, NotNil) + require.Error(t, err) tk.MustExec("rollback") tk.MustExec(`drop table if exists replace_test_3`) @@ -1221,19 +1246,19 @@ func (s *testSuite4) TestPartitionedTableReplace(c *C) { tk.MustExec(replaceUniqueIndexSQL) replaceUniqueIndexSQL = `replace into replace_test_3 set c2=8;` tk.MustExec(replaceUniqueIndexSQL) - c.Assert(int64(tk.Se.AffectedRows()), Equals, int64(1)) - tk.CheckLastMessage("") + require.Equal(t, int64(1), int64(tk.Session().AffectedRows())) + require.Empty(t, tk.Session().LastMessage()) replaceUniqueIndexSQL = `replace into replace_test_3 set c1=8, c2=8;` tk.MustExec(replaceUniqueIndexSQL) - c.Assert(int64(tk.Se.AffectedRows()), Equals, int64(2)) - tk.CheckLastMessage("") + require.Equal(t, int64(2), int64(tk.Session().AffectedRows())) + require.Empty(t, tk.Session().LastMessage()) replaceUniqueIndexSQL = `replace into replace_test_3 set c2=NULL;` tk.MustExec(replaceUniqueIndexSQL) replaceUniqueIndexSQL = `replace into replace_test_3 set c2=NULL;` tk.MustExec(replaceUniqueIndexSQL) - c.Assert(int64(tk.Se.AffectedRows()), Equals, int64(1)) - tk.CheckLastMessage("") + require.Equal(t, int64(1), int64(tk.Session().AffectedRows())) + require.Empty(t, tk.Session().LastMessage()) replaceUniqueIndexSQL = `create table replace_test_4 (c1 int, c2 int, c3 int, UNIQUE INDEX (c1, c2)) partition by range (c1) ( PARTITION p0 VALUES LESS THAN (4), @@ -1245,7 +1270,7 @@ func (s *testSuite4) TestPartitionedTableReplace(c *C) { tk.MustExec(replaceUniqueIndexSQL) replaceUniqueIndexSQL = `replace into replace_test_4 set c2=NULL;` tk.MustExec(replaceUniqueIndexSQL) - c.Assert(int64(tk.Se.AffectedRows()), Equals, int64(1)) + require.Equal(t, int64(1), int64(tk.Session().AffectedRows())) replacePrimaryKeySQL := `create table replace_test_5 (c1 int, c2 int, c3 int, PRIMARY KEY (c1, c2)) partition by range (c2) ( PARTITION p0 VALUES LESS THAN (4), @@ -1256,7 +1281,7 @@ func (s *testSuite4) TestPartitionedTableReplace(c *C) { tk.MustExec(replacePrimaryKeySQL) replacePrimaryKeySQL = `replace into replace_test_5 set c1=1, c2=2;` tk.MustExec(replacePrimaryKeySQL) - c.Assert(int64(tk.Se.AffectedRows()), Equals, int64(1)) + require.Equal(t, int64(1), int64(tk.Session().AffectedRows())) issue989SQL := `CREATE TABLE tIssue989 (a int, b int, KEY(a), UNIQUE KEY(b)) partition by range (b) ( PARTITION p1 VALUES LESS THAN (100), @@ -1270,8 +1295,11 @@ func (s *testSuite4) TestPartitionedTableReplace(c *C) { r.Check(testkit.Rows("111 2")) } -func (s *testSuite4) TestHashPartitionedTableReplace(c *C) { - tk := testkit.NewTestKit(c, s.store) +func TestHashPartitionedTableReplace(t *testing.T) { + t.Parallel() + store, clean := testkit.CreateMockStore(t) + defer clean() + tk := testkit.NewTestKit(t, store) tk.MustExec("use test") tk.MustExec("set @@session.tidb_enable_table_partition = '1';") tk.MustExec("drop table if exists replace_test;") @@ -1285,37 +1313,37 @@ func (s *testSuite4) TestHashPartitionedTableReplace(c *C) { errReplaceSQL := `replace replace_test (c1) values ();` tk.MustExec("begin") _, err := tk.Exec(errReplaceSQL) - c.Assert(err, NotNil) + require.Error(t, err) tk.MustExec("rollback") errReplaceSQL = `replace replace_test (c1, c2) values (1,2),(1);` tk.MustExec("begin") _, err = tk.Exec(errReplaceSQL) - c.Assert(err, NotNil) + require.Error(t, err) tk.MustExec("rollback") errReplaceSQL = `replace replace_test (xxx) values (3);` tk.MustExec("begin") _, err = tk.Exec(errReplaceSQL) - c.Assert(err, NotNil) + require.Error(t, err) tk.MustExec("rollback") errReplaceSQL = `replace replace_test_xxx (c1) values ();` tk.MustExec("begin") _, err = tk.Exec(errReplaceSQL) - c.Assert(err, NotNil) + require.Error(t, err) tk.MustExec("rollback") errReplaceSetSQL := `replace replace_test set c1 = 4, c1 = 5;` tk.MustExec("begin") _, err = tk.Exec(errReplaceSetSQL) - c.Assert(err, NotNil) + require.Error(t, err) tk.MustExec("rollback") errReplaceSetSQL = `replace replace_test set xxx = 6;` tk.MustExec("begin") _, err = tk.Exec(errReplaceSetSQL) - c.Assert(err, NotNil) + require.Error(t, err) tk.MustExec("rollback") tk.MustExec(`replace replace_test set c1 = 3;`) @@ -1336,7 +1364,7 @@ func (s *testSuite4) TestHashPartitionedTableReplace(c *C) { errReplaceSelectSQL := `replace replace_test_1 select c1 from replace_test;` tk.MustExec("begin") _, err = tk.Exec(errReplaceSelectSQL) - c.Assert(err, NotNil) + require.Error(t, err) tk.MustExec("rollback") tk.MustExec(`drop table if exists replace_test_3`) @@ -1345,13 +1373,13 @@ func (s *testSuite4) TestHashPartitionedTableReplace(c *C) { tk.MustExec(`replace into replace_test_3 set c2=8;`) tk.MustExec(`replace into replace_test_3 set c2=8;`) - c.Assert(int64(tk.Se.AffectedRows()), Equals, int64(1)) + require.Equal(t, int64(1), int64(tk.Session().AffectedRows())) tk.MustExec(`replace into replace_test_3 set c1=8, c2=8;`) - c.Assert(int64(tk.Se.AffectedRows()), Equals, int64(2)) + require.Equal(t, int64(2), int64(tk.Session().AffectedRows())) tk.MustExec(`replace into replace_test_3 set c2=NULL;`) tk.MustExec(`replace into replace_test_3 set c2=NULL;`) - c.Assert(int64(tk.Se.AffectedRows()), Equals, int64(1)) + require.Equal(t, int64(1), int64(tk.Session().AffectedRows())) for i := 0; i < 100; i++ { sql := fmt.Sprintf("replace into replace_test_3 set c2=%d;", i) @@ -1367,7 +1395,7 @@ func (s *testSuite4) TestHashPartitionedTableReplace(c *C) { tk.MustExec(replaceUniqueIndexSQL) replaceUniqueIndexSQL = `replace into replace_test_4 set c2=NULL;` tk.MustExec(replaceUniqueIndexSQL) - c.Assert(int64(tk.Se.AffectedRows()), Equals, int64(1)) + require.Equal(t, int64(1), int64(tk.Session().AffectedRows())) replacePrimaryKeySQL := `create table replace_test_5 (c1 int, c2 int, c3 int, PRIMARY KEY (c1, c2)) partition by hash (c2) partitions 9;` tk.MustExec(replacePrimaryKeySQL) @@ -1375,7 +1403,7 @@ func (s *testSuite4) TestHashPartitionedTableReplace(c *C) { tk.MustExec(replacePrimaryKeySQL) replacePrimaryKeySQL = `replace into replace_test_5 set c1=1, c2=2;` tk.MustExec(replacePrimaryKeySQL) - c.Assert(int64(tk.Se.AffectedRows()), Equals, int64(1)) + require.Equal(t, int64(1), int64(tk.Session().AffectedRows())) issue989SQL := `CREATE TABLE tIssue989 (a int, b int, KEY(a), UNIQUE KEY(b)) partition by hash (b) partitions 10;` tk.MustExec(issue989SQL) @@ -1387,269 +1415,11 @@ func (s *testSuite4) TestHashPartitionedTableReplace(c *C) { r.Check(testkit.Rows("111 2")) } -func (s *testSuite8) TestUpdate(c *C) { - tk := testkit.NewTestKit(c, s.store) - tk.MustExec("use test") - s.fillData(tk, "update_test") - - updateStr := `UPDATE update_test SET name = "abc" where id > 0;` - tk.MustExec(updateStr) - tk.CheckExecResult(2, 0) - tk.CheckLastMessage("Rows matched: 2 Changed: 2 Warnings: 0") - - // select data - tk.MustExec("begin") - r := tk.MustQuery(`SELECT * from update_test limit 2;`) - r.Check(testkit.Rows("1 abc", "2 abc")) - tk.MustExec("commit") - - tk.MustExec(`UPDATE update_test SET name = "foo"`) - tk.CheckExecResult(2, 0) - tk.CheckLastMessage("Rows matched: 2 Changed: 2 Warnings: 0") - - // table option is auto-increment - tk.MustExec("begin") - tk.MustExec("drop table if exists update_test;") - tk.MustExec("commit") - tk.MustExec("begin") - tk.MustExec("create table update_test(id int not null auto_increment, name varchar(255), primary key(id))") - tk.MustExec("insert into update_test(name) values ('aa')") - tk.MustExec("update update_test set id = 8 where name = 'aa'") - tk.CheckLastMessage("Rows matched: 1 Changed: 1 Warnings: 0") - tk.MustExec("insert into update_test(name) values ('bb')") - tk.MustExec("commit") - tk.MustExec("begin") - r = tk.MustQuery("select * from update_test;") - r.Check(testkit.Rows("8 aa", "9 bb")) - tk.MustExec("commit") - - tk.MustExec("begin") - tk.MustExec("drop table if exists update_test;") - tk.MustExec("commit") - tk.MustExec("begin") - tk.MustExec("create table update_test(id int not null auto_increment, name varchar(255), index(id))") - tk.MustExec("insert into update_test(name) values ('aa')") - _, err := tk.Exec("update update_test set id = null where name = 'aa'") - c.Assert(err, NotNil) - c.Assert(err.Error(), DeepEquals, "[table:1048]Column 'id' cannot be null") - - tk.MustExec("drop table update_test") - tk.MustExec("create table update_test(id int)") - tk.MustExec("begin") - tk.MustExec("insert into update_test(id) values (1)") - tk.MustExec("update update_test set id = 2 where id = 1 limit 1") - tk.CheckLastMessage("Rows matched: 1 Changed: 1 Warnings: 0") - r = tk.MustQuery("select * from update_test;") - r.Check(testkit.Rows("2")) - tk.MustExec("commit") - - // Test that in a transaction, when a constraint failed in an update statement, the record is not inserted. - tk.MustExec("create table update_unique (id int primary key, name int unique)") - tk.MustExec("insert update_unique values (1, 1), (2, 2);") - tk.MustExec("begin") - _, err = tk.Exec("update update_unique set name = 1 where id = 2") - c.Assert(err, NotNil) - tk.MustExec("commit") - tk.MustQuery("select * from update_unique").Check(testkit.Rows("1 1", "2 2")) - - // test update ignore for pimary key - tk.MustExec("drop table if exists t;") - tk.MustExec("create table t(a bigint, primary key (a));") - tk.MustExec("insert into t values (1)") - tk.MustExec("insert into t values (2)") - _, err = tk.Exec("update ignore t set a = 1 where a = 2;") - c.Assert(err, IsNil) - tk.CheckLastMessage("Rows matched: 1 Changed: 0 Warnings: 1") - r = tk.MustQuery("SHOW WARNINGS;") - r.Check(testkit.Rows("Warning 1062 Duplicate entry '1' for key 'PRIMARY'")) - tk.MustQuery("select * from t").Check(testkit.Rows("1", "2")) - - // test update ignore for truncate as warning - _, err = tk.Exec("update ignore t set a = 1 where a = (select '2a')") - c.Assert(err, IsNil) - r = tk.MustQuery("SHOW WARNINGS;") - r.Check(testkit.Rows("Warning 1292 Truncated incorrect DOUBLE value: '2a'", "Warning 1292 Truncated incorrect DOUBLE value: '2a'", "Warning 1062 Duplicate entry '1' for key 'PRIMARY'")) - - tk.MustExec("update ignore t set a = 42 where a = 2;") - tk.MustQuery("select * from t").Check(testkit.Rows("1", "42")) - - // test update ignore for unique key - tk.MustExec("drop table if exists t;") - tk.MustExec("create table t(a bigint, unique key I_uniq (a));") - tk.MustExec("insert into t values (1)") - tk.MustExec("insert into t values (2)") - _, err = tk.Exec("update ignore t set a = 1 where a = 2;") - c.Assert(err, IsNil) - tk.CheckLastMessage("Rows matched: 1 Changed: 0 Warnings: 1") - r = tk.MustQuery("SHOW WARNINGS;") - r.Check(testkit.Rows("Warning 1062 Duplicate entry '1' for key 'I_uniq'")) - tk.MustQuery("select * from t").Check(testkit.Rows("1", "2")) - - // test issue21965 - tk.MustExec("drop table if exists t;") - tk.MustExec("set @@session.tidb_enable_list_partition = ON") - tk.MustExec("create table t (a int) partition by list (a) (partition p0 values in (0,1));") - tk.MustExec("insert ignore into t values (1);") - tk.MustExec("update ignore t set a=2 where a=1;") - tk.CheckLastMessage("Rows matched: 1 Changed: 0 Warnings: 0") - tk.MustExec("drop table if exists t;") - tk.MustExec("create table t (a int key) partition by list (a) (partition p0 values in (0,1));") - tk.MustExec("insert ignore into t values (1);") - tk.MustExec("update ignore t set a=2 where a=1;") - tk.CheckLastMessage("Rows matched: 1 Changed: 0 Warnings: 0") - - tk.MustExec("drop table if exists t") - tk.MustExec("create table t(id integer auto_increment, t1 datetime, t2 datetime, primary key (id))") - tk.MustExec("insert into t(t1, t2) values('2000-10-01 01:01:01', '2017-01-01 10:10:10')") - tk.MustQuery("select * from t").Check(testkit.Rows("1 2000-10-01 01:01:01 2017-01-01 10:10:10")) - tk.MustExec("update t set t1 = '2017-10-01 10:10:11', t2 = date_add(t1, INTERVAL 10 MINUTE) where id = 1") - tk.CheckLastMessage("Rows matched: 1 Changed: 1 Warnings: 0") - tk.MustQuery("select * from t").Check(testkit.Rows("1 2017-10-01 10:10:11 2000-10-01 01:11:01")) - - // for issue #5132 - tk.MustExec("CREATE TABLE `tt1` (" + - "`a` int(11) NOT NULL," + - "`b` varchar(32) DEFAULT NULL," + - "`c` varchar(32) DEFAULT NULL," + - "PRIMARY KEY (`a`)," + - "UNIQUE KEY `b_idx` (`b`)" + - ") ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;") - tk.MustExec("insert into tt1 values(1, 'a', 'a');") - tk.MustExec("insert into tt1 values(2, 'd', 'b');") - r = tk.MustQuery("select * from tt1;") - r.Check(testkit.Rows("1 a a", "2 d b")) - tk.MustExec("update tt1 set a=5 where c='b';") - tk.CheckLastMessage("Rows matched: 1 Changed: 1 Warnings: 0") - r = tk.MustQuery("select * from tt1;") - r.Check(testkit.Rows("1 a a", "5 d b")) - - // Automatic Updating for TIMESTAMP - tk.MustExec("CREATE TABLE `tsup` (" + - "`a` int," + - "`ts` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP," + - "KEY `idx` (`ts`)" + - ");") - tk.MustExec("set @orig_sql_mode=@@sql_mode; set @@sql_mode='';") - tk.MustExec("insert into tsup values(1, '0000-00-00 00:00:00');") - tk.MustExec("update tsup set a=5;") - tk.CheckLastMessage("Rows matched: 1 Changed: 1 Warnings: 0") - r1 := tk.MustQuery("select ts from tsup use index (idx);") - r2 := tk.MustQuery("select ts from tsup;") - r1.Check(r2.Rows()) - tk.MustExec("update tsup set ts='2019-01-01';") - tk.MustQuery("select ts from tsup;").Check(testkit.Rows("2019-01-01 00:00:00")) - tk.MustExec("set @@sql_mode=@orig_sql_mode;") - - // issue 5532 - tk.MustExec("create table decimals (a decimal(20, 0) not null)") - tk.MustExec("insert into decimals values (201)") - // A warning rather than data truncated error. - tk.MustExec("update decimals set a = a + 1.23;") - tk.CheckLastMessage("Rows matched: 1 Changed: 1 Warnings: 1") - tk.MustQuery("show warnings").Check(testkit.Rows("Warning 1292 Truncated incorrect DECIMAL value: '202.23'")) - r = tk.MustQuery("select * from decimals") - r.Check(testkit.Rows("202")) - - tk.MustExec("drop table t") - tk.MustExec("CREATE TABLE `t` ( `c1` year DEFAULT NULL, `c2` year DEFAULT NULL, `c3` date DEFAULT NULL, `c4` datetime DEFAULT NULL, KEY `idx` (`c1`,`c2`))") - _, err = tk.Exec("UPDATE t SET c2=16777215 WHERE c1>= -8388608 AND c1 < -9 ORDER BY c1 LIMIT 2") - c.Assert(err, IsNil) - - tk.MustGetErrCode("update (select * from t) t set c1 = 1111111", mysql.ErrNonUpdatableTable) - - // test update ignore for bad null error - tk.MustExec("drop table if exists t;") - tk.MustExec(`create table t (i int not null default 10)`) - tk.MustExec("insert into t values (1)") - tk.MustExec("update ignore t set i = null;") - tk.CheckLastMessage("Rows matched: 1 Changed: 1 Warnings: 1") - r = tk.MustQuery("SHOW WARNINGS;") - r.Check(testkit.Rows("Warning 1048 Column 'i' cannot be null")) - tk.MustQuery("select * from t").Check(testkit.Rows("0")) - - // issue 7237, update subquery table should be forbidden - tk.MustExec("drop table t") - tk.MustExec("create table t (k int, v int)") - _, err = tk.Exec("update t, (select * from t) as b set b.k = t.k") - c.Assert(err.Error(), Equals, "[planner:1288]The target table b of the UPDATE is not updatable") - tk.MustExec("update t, (select * from t) as b set t.k = b.k") - - // issue 8045 - tk.MustExec("drop table if exists t1") - tk.MustExec(`CREATE TABLE t1 (c1 float)`) - tk.MustExec("INSERT INTO t1 SET c1 = 1") - tk.MustExec("UPDATE t1 SET c1 = 1.2 WHERE c1=1;") - tk.CheckLastMessage("Rows matched: 1 Changed: 1 Warnings: 0") - - // issue 8119 - tk.MustExec("drop table if exists t;") - tk.MustExec("create table t (c1 float(1,1));") - tk.MustExec("insert into t values (0.0);") - _, err = tk.Exec("update t set c1 = 2.0;") - c.Assert(types.ErrWarnDataOutOfRange.Equal(err), IsTrue) - - tk.MustExec("drop table if exists t") - tk.MustExec("create table t(a datetime not null, b datetime)") - tk.MustExec("insert into t value('1999-12-12', '1999-12-13')") - tk.MustExec("set @orig_sql_mode=@@sql_mode; set @@sql_mode='';") - tk.MustQuery("select * from t").Check(testkit.Rows("1999-12-12 00:00:00 1999-12-13 00:00:00")) - tk.MustExec("update t set a = ''") - tk.MustQuery("select * from t").Check(testkit.Rows("0000-00-00 00:00:00 1999-12-13 00:00:00")) - tk.MustExec("update t set b = ''") - tk.MustQuery("select * from t").Check(testkit.Rows("0000-00-00 00:00:00 0000-00-00 00:00:00")) - tk.MustExec("set @@sql_mode=@orig_sql_mode;") - - tk.MustExec("create view v as select * from t") - _, err = tk.Exec("update v set a = '2000-11-11'") - c.Assert(err.Error(), Equals, core.ErrViewInvalid.GenWithStackByArgs("test", "v").Error()) - tk.MustExec("drop view v") - - tk.MustExec("create sequence seq") - tk.MustGetErrCode("update seq set minvalue=1", mysql.ErrBadField) - tk.MustExec("drop sequence seq") - - tk.MustExec("drop table if exists t1, t2") - tk.MustExec("create table t1(a int, b int, c int, d int, e int, index idx(a))") - tk.MustExec("create table t2(a int, b int, c int)") - tk.MustExec("update t1 join t2 on t1.a=t2.a set t1.a=1 where t2.b=1 and t2.c=2") - - // Assign `DEFAULT` in `UPDATE` statement - tk.MustExec("drop table if exists t1, t2;") - tk.MustExec("create table t1 (a int default 1, b int default 2);") - tk.MustExec("insert into t1 values (10, 10), (20, 20);") - tk.MustExec("update t1 set a=default where b=10;") - tk.MustQuery("select * from t1;").Check(testkit.Rows("1 10", "20 20")) - tk.MustExec("update t1 set a=30, b=default where a=20;") - tk.MustQuery("select * from t1;").Check(testkit.Rows("1 10", "30 2")) - tk.MustExec("update t1 set a=default, b=default where a=30;") - tk.MustQuery("select * from t1;").Check(testkit.Rows("1 10", "1 2")) - tk.MustExec("insert into t1 values (40, 40)") - tk.MustExec("update t1 set a=default, b=default") - tk.MustQuery("select * from t1;").Check(testkit.Rows("1 2", "1 2", "1 2")) - tk.MustExec("update t1 set a=default(b), b=default(a)") - tk.MustQuery("select * from t1;").Check(testkit.Rows("2 1", "2 1", "2 1")) - // With generated columns - tk.MustExec("create table t2 (a int default 1, b int generated always as (-a) virtual, c int generated always as (-a) stored);") - tk.MustExec("insert into t2 values (10, default, default), (20, default, default)") - tk.MustExec("update t2 set b=default;") - tk.MustQuery("select * from t2;").Check(testkit.Rows("10 -10 -10", "20 -20 -20")) - tk.MustExec("update t2 set a=30, b=default where a=10;") - tk.MustQuery("select * from t2;").Check(testkit.Rows("30 -30 -30", "20 -20 -20")) - tk.MustExec("update t2 set c=default, a=40 where c=-20;") - tk.MustQuery("select * from t2;").Check(testkit.Rows("30 -30 -30", "40 -40 -40")) - tk.MustExec("update t2 set a=default, b=default, c=default where b=-30;") - tk.MustQuery("select * from t2;").Check(testkit.Rows("1 -1 -1", "40 -40 -40")) - tk.MustExec("update t2 set a=default(a), b=default, c=default;") - tk.MustQuery("select * from t2;").Check(testkit.Rows("1 -1 -1", "1 -1 -1")) - tk.MustGetErrCode("update t2 set b=default(a);", mysql.ErrBadGeneratedColumn) - tk.MustGetErrCode("update t2 set a=default(b), b=default(b);", mysql.ErrBadGeneratedColumn) - tk.MustGetErrCode("update t2 set a=default(a), c=default(c);", mysql.ErrBadGeneratedColumn) - tk.MustGetErrCode("update t2 set a=default(a), c=default(a);", mysql.ErrBadGeneratedColumn) - tk.MustExec("drop table t1, t2") -} - -func (s *testSuite4) TestPartitionedTableUpdate(c *C) { - tk := testkit.NewTestKit(c, s.store) +func TestPartitionedTableUpdate(t *testing.T) { + t.Parallel() + store, clean := testkit.CreateMockStore(t) + defer clean() + tk := testkit.NewTestKit(t, store) tk.MustExec("use test") tk.MustExec("drop table if exists t") tk.MustExec(`create table t (id int not null default 1, name varchar(255)) @@ -1667,21 +1437,21 @@ func (s *testSuite4) TestPartitionedTableUpdate(c *C) { // update non partition column tk.MustExec(`UPDATE t SET name = "abc" where id > 0;`) tk.CheckExecResult(2, 0) - tk.CheckLastMessage("Rows matched: 2 Changed: 2 Warnings: 0") + require.Equal(t, tk.Session().LastMessage(), "Rows matched: 2 Changed: 2 Warnings: 0") r := tk.MustQuery(`SELECT * from t order by id limit 2;`) r.Check(testkit.Rows("1 abc", "7 abc")) // update partition column tk.MustExec(`update t set id = id + 1`) tk.CheckExecResult(2, 0) - tk.CheckLastMessage("Rows matched: 2 Changed: 2 Warnings: 0") + require.Equal(t, tk.Session().LastMessage(), "Rows matched: 2 Changed: 2 Warnings: 0") r = tk.MustQuery(`SELECT * from t order by id limit 2;`) r.Check(testkit.Rows("2 abc", "8 abc")) // update partition column, old and new record locates on different partitions tk.MustExec(`update t set id = 20 where id = 8`) tk.CheckExecResult(1, 0) - tk.CheckLastMessage("Rows matched: 1 Changed: 1 Warnings: 0") + require.Equal(t, tk.Session().LastMessage(), "Rows matched: 1 Changed: 1 Warnings: 0") r = tk.MustQuery(`SELECT * from t order by id limit 2;`) r.Check(testkit.Rows("2 abc", "20 abc")) @@ -1696,14 +1466,13 @@ func (s *testSuite4) TestPartitionedTableUpdate(c *C) { tk.MustExec("insert into t(name) values ('aa')") tk.MustExec("update t set id = 8 where name = 'aa'") - tk.CheckLastMessage("Rows matched: 1 Changed: 1 Warnings: 0") + require.Equal(t, tk.Session().LastMessage(), "Rows matched: 1 Changed: 1 Warnings: 0") tk.MustExec("insert into t(name) values ('bb')") r = tk.MustQuery("select * from t;") r.Check(testkit.Rows("8 aa", "9 bb")) _, err := tk.Exec("update t set id = null where name = 'aa'") - c.Assert(err, NotNil) - c.Assert(err.Error(), DeepEquals, "[table:1048]Column 'id' cannot be null") + require.EqualError(t, err, "[table:1048]Column 'id' cannot be null") // Test that in a transaction, when a constraint failed in an update statement, the record is not inserted. tk.MustExec("drop table if exists t;") @@ -1715,7 +1484,7 @@ func (s *testSuite4) TestPartitionedTableUpdate(c *C) { PARTITION p3 VALUES LESS THAN (21))`) tk.MustExec("insert t values (1, 1), (2, 2);") _, err = tk.Exec("update t set name = 1 where id = 2") - c.Assert(err, NotNil) + require.Error(t, err) tk.MustQuery("select * from t").Check(testkit.Rows("1 1", "2 2")) // test update ignore for pimary key @@ -1727,15 +1496,15 @@ func (s *testSuite4) TestPartitionedTableUpdate(c *C) { tk.MustExec("insert into t values (5)") tk.MustExec("insert into t values (7)") _, err = tk.Exec("update ignore t set a = 5 where a = 7;") - c.Assert(err, IsNil) - tk.CheckLastMessage("Rows matched: 1 Changed: 0 Warnings: 1") + require.NoError(t, err) + require.Equal(t, tk.Session().LastMessage(), "Rows matched: 1 Changed: 0 Warnings: 1") r = tk.MustQuery("SHOW WARNINGS;") r.Check(testkit.Rows("Warning 1062 Duplicate entry '5' for key 'PRIMARY'")) tk.MustQuery("select * from t order by a").Check(testkit.Rows("5", "7")) // test update ignore for truncate as warning _, err = tk.Exec("update ignore t set a = 1 where a = (select '2a')") - c.Assert(err, IsNil) + require.NoError(t, err) r = tk.MustQuery("SHOW WARNINGS;") r.Check(testkit.Rows("Warning 1292 Truncated incorrect DOUBLE value: '2a'", "Warning 1292 Truncated incorrect DOUBLE value: '2a'")) @@ -1748,16 +1517,19 @@ func (s *testSuite4) TestPartitionedTableUpdate(c *C) { tk.MustExec("insert into t values (5)") tk.MustExec("insert into t values (7)") _, err = tk.Exec("update ignore t set a = 5 where a = 7;") - c.Assert(err, IsNil) - tk.CheckLastMessage("Rows matched: 1 Changed: 0 Warnings: 1") + require.NoError(t, err) + require.Equal(t, tk.Session().LastMessage(), "Rows matched: 1 Changed: 0 Warnings: 1") r = tk.MustQuery("SHOW WARNINGS;") r.Check(testkit.Rows("Warning 1062 Duplicate entry '5' for key 'I_uniq'")) tk.MustQuery("select * from t order by a").Check(testkit.Rows("5", "7")) } // TestUpdateCastOnlyModifiedValues for issue #4514. -func (s *testSuite4) TestUpdateCastOnlyModifiedValues(c *C) { - tk := testkit.NewTestKit(c, s.store) +func TestUpdateCastOnlyModifiedValues(t *testing.T) { + t.Parallel() + store, clean := testkit.CreateMockStore(t) + defer clean() + tk := testkit.NewTestKit(t, store) tk.MustExec("use test") tk.MustExec("create table update_modified (col_1 int, col_2 enum('a', 'b'))") tk.MustExec("set SQL_MODE=''") @@ -1766,15 +1538,15 @@ func (s *testSuite4) TestUpdateCastOnlyModifiedValues(c *C) { r.Check(testkit.Rows("0 ")) tk.MustExec("set SQL_MODE=STRICT_ALL_TABLES") tk.MustExec("update update_modified set col_1 = 1") - tk.CheckLastMessage("Rows matched: 1 Changed: 1 Warnings: 0") + require.Equal(t, tk.Session().LastMessage(), "Rows matched: 1 Changed: 1 Warnings: 0") r = tk.MustQuery("SELECT * FROM update_modified") r.Check(testkit.Rows("1 ")) _, err := tk.Exec("update update_modified set col_1 = 2, col_2 = 'c'") - c.Assert(err, NotNil) + require.Error(t, err) r = tk.MustQuery("SELECT * FROM update_modified") r.Check(testkit.Rows("1 ")) tk.MustExec("update update_modified set col_1 = 3, col_2 = 'a'") - tk.CheckLastMessage("Rows matched: 1 Changed: 1 Warnings: 0") + require.Equal(t, tk.Session().LastMessage(), "Rows matched: 1 Changed: 1 Warnings: 0") r = tk.MustQuery("SELECT * FROM update_modified") r.Check(testkit.Rows("3 a")) @@ -1782,16 +1554,16 @@ func (s *testSuite4) TestUpdateCastOnlyModifiedValues(c *C) { tk.MustExec(`CREATE TABLE update_with_diff_type (a int, b JSON)`) tk.MustExec(`INSERT INTO update_with_diff_type VALUES(3, '{"a": "测试"}')`) tk.MustExec(`UPDATE update_with_diff_type SET a = '300'`) - tk.CheckLastMessage("Rows matched: 1 Changed: 1 Warnings: 0") + require.Equal(t, tk.Session().LastMessage(), "Rows matched: 1 Changed: 1 Warnings: 0") r = tk.MustQuery("SELECT a FROM update_with_diff_type") r.Check(testkit.Rows("300")) tk.MustExec(`UPDATE update_with_diff_type SET b = '{"a": "\\u6d4b\\u8bd5"}'`) - tk.CheckLastMessage("Rows matched: 1 Changed: 0 Warnings: 0") + require.Equal(t, tk.Session().LastMessage(), "Rows matched: 1 Changed: 0 Warnings: 0") r = tk.MustQuery("SELECT b FROM update_with_diff_type") r.Check(testkit.Rows(`{"a": "测试"}`)) } -func (s *testSuite4) fillMultiTableForUpdate(tk *testkit.TestKit) { +func fillMultiTableForUpdate(tk *testkit.TestKit) { // Create and fill table items tk.MustExec("CREATE TABLE items (id int, price TEXT);") tk.MustExec(`insert into items values (11, "items_price_11"), (12, "items_price_12"), (13, "items_price_13");`) @@ -1802,13 +1574,16 @@ func (s *testSuite4) fillMultiTableForUpdate(tk *testkit.TestKit) { tk.CheckExecResult(3, 0) } -func (s *testSuite4) TestMultipleTableUpdate(c *C) { - tk := testkit.NewTestKit(c, s.store) +func TestMultipleTableUpdate(t *testing.T) { + t.Parallel() + store, clean := testkit.CreateMockStore(t) + defer clean() + tk := testkit.NewTestKit(t, store) tk.MustExec("use test") - s.fillMultiTableForUpdate(tk) + fillMultiTableForUpdate(tk) tk.MustExec(`UPDATE items, month SET items.price=month.mprice WHERE items.id=month.mid;`) - tk.CheckLastMessage("Rows matched: 2 Changed: 2 Warnings: 0") + require.Equal(t, tk.Session().LastMessage(), "Rows matched: 2 Changed: 2 Warnings: 0") tk.MustExec("begin") r := tk.MustQuery("SELECT * FROM items") r.Check(testkit.Rows("11 month_price_11", "12 items_price_12", "13 month_price_13")) @@ -1816,7 +1591,7 @@ func (s *testSuite4) TestMultipleTableUpdate(c *C) { // Single-table syntax but with multiple tables tk.MustExec(`UPDATE items join month on items.id=month.mid SET items.price=month.mid;`) - tk.CheckLastMessage("Rows matched: 2 Changed: 2 Warnings: 0") + require.Equal(t, tk.Session().LastMessage(), "Rows matched: 2 Changed: 2 Warnings: 0") tk.MustExec("begin") r = tk.MustQuery("SELECT * FROM items") r.Check(testkit.Rows("11 11", "12 items_price_12", "13 13")) @@ -1824,7 +1599,7 @@ func (s *testSuite4) TestMultipleTableUpdate(c *C) { // JoinTable with alias table name. tk.MustExec(`UPDATE items T0 join month T1 on T0.id=T1.mid SET T0.price=T1.mprice;`) - tk.CheckLastMessage("Rows matched: 2 Changed: 2 Warnings: 0") + require.Equal(t, tk.Session().LastMessage(), "Rows matched: 2 Changed: 2 Warnings: 0") tk.MustExec("begin") r = tk.MustQuery("SELECT * FROM items") r.Check(testkit.Rows("11 month_price_11", "12 items_price_12", "13 month_price_13")) @@ -1839,7 +1614,7 @@ func (s *testSuite4) TestMultipleTableUpdate(c *C) { insert into t2 values ("a"), ("b"); update t1, t2 set t1.c = 10, t2.c = "abc";` tk.MustExec(testSQL) - tk.CheckLastMessage("Rows matched: 4 Changed: 4 Warnings: 0") + require.Equal(t, tk.Session().LastMessage(), "Rows matched: 4 Changed: 4 Warnings: 0") // fix https://github.com/pingcap/tidb/issues/376 testSQL = `DROP TABLE IF EXISTS t1, t2; @@ -1849,7 +1624,7 @@ func (s *testSuite4) TestMultipleTableUpdate(c *C) { insert into t2 values (1), (2); update t1, t2 set t1.c1 = 10, t2.c2 = 2 where t2.c2 = 1;` tk.MustExec(testSQL) - tk.CheckLastMessage("Rows matched: 3 Changed: 3 Warnings: 0") + require.Equal(t, tk.Session().LastMessage(), "Rows matched: 3 Changed: 3 Warnings: 0") r = tk.MustQuery("select * from t1") r.Check(testkit.Rows("10", "10")) @@ -1858,18 +1633,21 @@ func (s *testSuite4) TestMultipleTableUpdate(c *C) { tk.MustExec("drop table if exists t, t") tk.MustExec("create table t (a int, b int)") tk.MustExec("insert into t values(1, 1), (2, 2), (3, 3)") - tk.CheckLastMessage("Records: 3 Duplicates: 0 Warnings: 0") + require.Equal(t, tk.Session().LastMessage(), "Records: 3 Duplicates: 0 Warnings: 0") tk.MustExec("update t m, t n set m.a = m.a + 1") - tk.CheckLastMessage("Rows matched: 3 Changed: 3 Warnings: 0") + require.Equal(t, tk.Session().LastMessage(), "Rows matched: 3 Changed: 3 Warnings: 0") tk.MustQuery("select * from t").Check(testkit.Rows("2 1", "3 2", "4 3")) tk.MustExec("update t m, t n set n.a = n.a - 1, n.b = n.b + 1") - tk.CheckLastMessage("Rows matched: 3 Changed: 3 Warnings: 0") + require.Equal(t, tk.Session().LastMessage(), "Rows matched: 3 Changed: 3 Warnings: 0") tk.MustQuery("select * from t").Check(testkit.Rows("1 2", "2 3", "3 4")) } -func (s *testSuite) TestDelete(c *C) { - tk := testkit.NewTestKit(c, s.store) - s.fillData(tk, "delete_test") +func TestDelete(t *testing.T) { + t.Parallel() + store, clean := testkit.CreateMockStore(t) + defer clean() + tk := testkit.NewTestKit(t, store) + fillData(tk, "delete_test") tk.MustExec(`update delete_test set name = "abc" where id = 2;`) tk.CheckExecResult(1, 0) @@ -1894,9 +1672,9 @@ func (s *testSuite) TestDelete(c *C) { // Test delete ignore tk.MustExec("insert into delete_test values (2, 'abc')") _, err := tk.Exec("delete from delete_test where id = (select '2a')") - c.Assert(err, NotNil) + require.Error(t, err) _, err = tk.Exec("delete ignore from delete_test where id = (select '2a')") - c.Assert(err, IsNil) + require.NoError(t, err) tk.CheckExecResult(1, 0) r := tk.MustQuery("SHOW WARNINGS;") r.Check(testkit.Rows("Warning 1292 Truncated incorrect DOUBLE value: '2a'", "Warning 1292 Truncated incorrect DOUBLE value: '2a'")) @@ -1906,16 +1684,16 @@ func (s *testSuite) TestDelete(c *C) { tk.MustExec("create view v as select * from delete_test") _, err = tk.Exec("delete from v where name = 'aaa'") - c.Assert(err.Error(), Equals, core.ErrViewInvalid.GenWithStackByArgs("test", "v").Error()) + require.EqualError(t, err, core.ErrViewInvalid.GenWithStackByArgs("test", "v").Error()) tk.MustExec("drop view v") tk.MustExec("create sequence seq") _, err = tk.Exec("delete from seq") - c.Assert(err.Error(), Equals, "delete sequence seq is not supported now.") + require.EqualError(t, err, "delete sequence seq is not supported now.") tk.MustExec("drop sequence seq") } -func (s *testSuite4) TestPartitionedTableDelete(c *C) { +func TestPartitionedTableDelete(t *testing.T) { createTable := `CREATE TABLE test.t (id int not null default 1, name varchar(255), index(id)) PARTITION BY RANGE ( id ) ( PARTITION p0 VALUES LESS THAN (6), @@ -1923,7 +1701,10 @@ func (s *testSuite4) TestPartitionedTableDelete(c *C) { PARTITION p2 VALUES LESS THAN (16), PARTITION p3 VALUES LESS THAN (21))` - tk := testkit.NewTestKit(c, s.store) + t.Parallel() + store, clean := testkit.CreateMockStore(t) + defer clean() + tk := testkit.NewTestKit(t, store) tk.MustExec("use test") tk.MustExec("drop table if exists t") tk.MustExec(createTable) @@ -1945,9 +1726,9 @@ func (s *testSuite4) TestPartitionedTableDelete(c *C) { // Test delete ignore tk.MustExec("insert into t values (2, 'abc')") _, err := tk.Exec("delete from t where id = (select '2a')") - c.Assert(err, NotNil) + require.Error(t, err) _, err = tk.Exec("delete ignore from t where id = (select '2a')") - c.Assert(err, IsNil) + require.NoError(t, err) tk.CheckExecResult(1, 0) r := tk.MustQuery("SHOW WARNINGS;") r.Check(testkit.Rows("Warning 1292 Truncated incorrect DOUBLE value: '2a'", "Warning 1292 Truncated incorrect DOUBLE value: '2a'")) @@ -1968,7 +1749,7 @@ func (s *testSuite4) TestPartitionedTableDelete(c *C) { tk.MustExec(`drop table t1;`) } -func (s *testSuite4) fillDataMultiTable(tk *testkit.TestKit) { +func fillDataMultiTable(tk *testkit.TestKit) { tk.MustExec("use test") tk.MustExec("drop table if exists t1, t2, t3") // Create and fill table t1 @@ -1985,20 +1766,26 @@ func (s *testSuite4) fillDataMultiTable(tk *testkit.TestKit) { tk.CheckExecResult(3, 0) } -func (s *testSuite4) TestMultiTableDelete(c *C) { - tk := testkit.NewTestKit(c, s.store) - s.fillDataMultiTable(tk) +func TestMultiTableDelete(t *testing.T) { + t.Parallel() + store, clean := testkit.CreateMockStore(t) + defer clean() + tk := testkit.NewTestKit(t, store) + fillDataMultiTable(tk) tk.MustExec(`delete t1, t2 from t1 inner join t2 inner join t3 where t1.id=t2.id and t2.id=t3.id;`) tk.CheckExecResult(2, 0) // Select data r := tk.MustQuery("select * from t3") - c.Assert(r.Rows(), HasLen, 3) + require.Len(t, r.Rows(), 3) } -func (s *testSuite4) TestQualifiedDelete(c *C) { - tk := testkit.NewTestKit(c, s.store) +func TestQualifiedDelete(t *testing.T) { + t.Parallel() + store, clean := testkit.CreateMockStore(t) + defer clean() + tk := testkit.NewTestKit(t, store) tk.MustExec("use test") tk.MustExec("drop table if exists t1") tk.MustExec("drop table if exists t2") @@ -2015,8 +1802,7 @@ func (s *testSuite4) TestQualifiedDelete(c *C) { tk.CheckExecResult(1, 0) r := tk.MustQuery("select * from t1") - c.Assert(r.Rows(), HasLen, 0) - + require.Len(t, r.Rows(), 0) tk.MustExec("insert into t1 values (1, 3)") tk.MustExec("delete from t1 as a where a.c1 = 1") tk.CheckExecResult(1, 0) @@ -2031,26 +1817,29 @@ func (s *testSuite4) TestQualifiedDelete(c *C) { tk.CheckExecResult(2, 0) _, err := tk.Exec("delete t1, t2 from t1 as a join t2 as b where a.c2 = b.c1") - c.Assert(err, NotNil) + require.Error(t, err) } -func (s *testSuite8) TestLoadDataMissingColumn(c *C) { - tk := testkit.NewTestKit(c, s.store) +func TestLoadDataMissingColumn(t *testing.T) { + t.Parallel() + store, clean := testkit.CreateMockStore(t) + defer clean() + tk := testkit.NewTestKit(t, store) tk.MustExec("use test") createSQL := `create table load_data_missing (id int, t timestamp not null)` tk.MustExec(createSQL) tk.MustExec("load data local infile '/tmp/nonexistence.csv' ignore into table load_data_missing") - ctx := tk.Se.(sessionctx.Context) + ctx := tk.Session().(sessionctx.Context) ld, ok := ctx.Value(executor.LoadDataVarKey).(*executor.LoadDataInfo) - c.Assert(ok, IsTrue) + require.True(t, ok) defer ctx.SetValue(executor.LoadDataVarKey, nil) - c.Assert(ld, NotNil) + require.NotNil(t, ld) deleteSQL := "delete from load_data_missing" selectSQL := "select id, hour(t), minute(t) from load_data_missing;" _, reachLimit, err := ld.InsertData(context.Background(), nil, nil) - c.Assert(err, IsNil) - c.Assert(reachLimit, IsFalse) + require.NoError(t, err) + require.False(t, reachLimit) r := tk.MustQuery(selectSQL) r.Check(nil) @@ -2060,7 +1849,7 @@ func (s *testSuite8) TestLoadDataMissingColumn(c *C) { tests := []testCase{ {nil, []byte("12\n"), []string{fmt.Sprintf("12|%v|%v", timeHour, timeMinute)}, nil, "Records: 1 Deleted: 0 Skipped: 0 Warnings: 0"}, } - checkCases(tests, ld, c, tk, ctx, selectSQL, deleteSQL) + checkCases(tests, ld, t, tk, ctx, selectSQL, deleteSQL) tk.MustExec("alter table load_data_missing add column t2 timestamp null") curTime = types.CurrentTime(mysql.TypeTimestamp) @@ -2070,22 +1859,24 @@ func (s *testSuite8) TestLoadDataMissingColumn(c *C) { tests = []testCase{ {nil, []byte("12\n"), []string{fmt.Sprintf("12|%v|%v|", timeHour, timeMinute)}, nil, "Records: 1 Deleted: 0 Skipped: 0 Warnings: 0"}, } - checkCases(tests, ld, c, tk, ctx, selectSQL, deleteSQL) - + checkCases(tests, ld, t, tk, ctx, selectSQL, deleteSQL) } -func (s *testSuite4) TestIssue18681(c *C) { - tk := testkit.NewTestKit(c, s.store) +func TestIssue18681(t *testing.T) { + t.Parallel() + store, clean := testkit.CreateMockStore(t) + defer clean() + tk := testkit.NewTestKit(t, store) tk.MustExec("use test") createSQL := `drop table if exists load_data_test; create table load_data_test (a bit(1),b bit(1),c bit(1),d bit(1));` tk.MustExec(createSQL) tk.MustExec("load data local infile '/tmp/nonexistence.csv' ignore into table load_data_test") - ctx := tk.Se.(sessionctx.Context) + ctx := tk.Session().(sessionctx.Context) ld, ok := ctx.Value(executor.LoadDataVarKey).(*executor.LoadDataInfo) - c.Assert(ok, IsTrue) + require.True(t, ok) defer ctx.SetValue(executor.LoadDataVarKey, nil) - c.Assert(ld, NotNil) + require.NotNil(t, ld) deleteSQL := "delete from load_data_test" selectSQL := "select bin(a), bin(b), bin(c), bin(d) from load_data_test;" @@ -2102,29 +1893,32 @@ func (s *testSuite4) TestIssue18681(c *C) { tests := []testCase{ {nil, []byte("true\tfalse\t0\t1\n"), []string{"1|0|0|1"}, nil, "Records: 1 Deleted: 0 Skipped: 0 Warnings: 0"}, } - checkCases(tests, ld, c, tk, ctx, selectSQL, deleteSQL) - c.Assert(sc.WarningCount(), Equals, uint16(0)) + checkCases(tests, ld, t, tk, ctx, selectSQL, deleteSQL) + require.Equal(t, uint16(0), sc.WarningCount()) } -func (s *testSuite4) TestLoadData(c *C) { +func TestLoadData(t *testing.T) { trivialMsg := "Records: 1 Deleted: 0 Skipped: 0 Warnings: 0" - tk := testkit.NewTestKit(c, s.store) + t.Parallel() + store, clean := testkit.CreateMockStore(t) + defer clean() + tk := testkit.NewTestKit(t, store) tk.MustExec("use test") createSQL := `drop table if exists load_data_test; create table load_data_test (id int PRIMARY KEY AUTO_INCREMENT, c1 int, c2 varchar(255) default "def", c3 int);` _, err := tk.Exec("load data local infile '/tmp/nonexistence.csv' into table load_data_test") - c.Assert(err, NotNil) + require.Error(t, err) tk.MustExec(createSQL) _, err = tk.Exec("load data infile '/tmp/nonexistence.csv' into table load_data_test") - c.Assert(err, NotNil) + require.Error(t, err) _, err = tk.Exec("load data local infile '/tmp/nonexistence.csv' replace into table load_data_test") - c.Assert(err, NotNil) + require.Error(t, err) tk.MustExec("load data local infile '/tmp/nonexistence.csv' ignore into table load_data_test") - ctx := tk.Se.(sessionctx.Context) + ctx := tk.Session().(sessionctx.Context) ld, ok := ctx.Value(executor.LoadDataVarKey).(*executor.LoadDataInfo) - c.Assert(ok, IsTrue) + require.True(t, ok) defer ctx.SetValue(executor.LoadDataVarKey, nil) - c.Assert(ld, NotNil) + require.NotNil(t, ld) deleteSQL := "delete from load_data_test" selectSQL := "select * from load_data_test;" @@ -2132,10 +1926,10 @@ func (s *testSuite4) TestLoadData(c *C) { ctx.GetSessionVars().StmtCtx.DupKeyAsWarning = true ctx.GetSessionVars().StmtCtx.BadNullAsWarning = true _, reachLimit, err := ld.InsertData(context.Background(), nil, nil) - c.Assert(err, IsNil) - c.Assert(reachLimit, IsFalse) + require.NoError(t, err) + require.False(t, reachLimit) err = ld.CheckAndInsertOneBatch(context.Background(), ld.GetRows(), ld.GetCurBatchCnt()) - c.Assert(err, IsNil) + require.NoError(t, err) ld.SetMaxRowsInBatch(20000) r := tk.MustQuery(selectSQL) r.Check(nil) @@ -2169,7 +1963,7 @@ func (s *testSuite4) TestLoadData(c *C) { // data1 != nil, data2 != nil, InsertData returns data isn't nil {[]byte("\t2\t3"), []byte("\t4\t5"), nil, []byte("\t2\t3\t4\t5"), "Records: 0 Deleted: 0 Skipped: 0 Warnings: 0"}, } - checkCases(tests, ld, c, tk, ctx, selectSQL, deleteSQL) + checkCases(tests, ld, t, tk, ctx, selectSQL, deleteSQL) // lines starting symbol is "" and terminated symbol length is 2, InsertData returns data is nil ld.LinesInfo.Terminated = "||" @@ -2185,7 +1979,7 @@ func (s *testSuite4) TestLoadData(c *C) { []string{"4|2|3|4", "5|22|33|", "6|222||"}, nil, "Records: 3 Deleted: 0 Skipped: 0 Warnings: 0"}, {[]byte("6\t2\t3"), []byte("4\t5||"), []string{"6|2|34|5"}, nil, trivialMsg}, } - checkCases(tests, ld, c, tk, ctx, selectSQL, deleteSQL) + checkCases(tests, ld, t, tk, ctx, selectSQL, deleteSQL) // fields and lines aren't default, InsertData returns data is nil ld.FieldsInfo.Terminated = "\\" @@ -2238,7 +2032,7 @@ func (s *testSuite4) TestLoadData(c *C) { []string{"1|2|3|4", "2|22|33|"}, []byte("#^"), "Records: 2 Deleted: 0 Skipped: 0 Warnings: 0"}, {[]byte("xx1\\2\\3"), []byte("\\4\\5|!#^"), nil, []byte("#^"), "Records: 0 Deleted: 0 Skipped: 0 Warnings: 0"}, } - checkCases(tests, ld, c, tk, ctx, selectSQL, deleteSQL) + checkCases(tests, ld, t, tk, ctx, selectSQL, deleteSQL) // lines starting symbol is the same as terminated symbol, InsertData returns data is nil ld.LinesInfo.Terminated = "xxx" @@ -2273,7 +2067,7 @@ func (s *testSuite4) TestLoadData(c *C) { {[]byte("xxx10\\2\\3\\4\\5x"), []byte("xx11\\22\\33xxxxxx12\\222xxx"), []string{"10|2|3|4", "40|||"}, []byte("xxx"), "Records: 2 Deleted: 0 Skipped: 0 Warnings: 1"}, } - checkCases(tests, ld, c, tk, ctx, selectSQL, deleteSQL) + checkCases(tests, ld, t, tk, ctx, selectSQL, deleteSQL) // test line terminator in field quoter ld.LinesInfo.Terminated = "\n" @@ -2281,7 +2075,7 @@ func (s *testSuite4) TestLoadData(c *C) { tests = []testCase{ {[]byte("xxx1\\1\\\"2\n\"\\3\nxxx4\\4\\\"5\n5\"\\6"), nil, []string{"1|1|2\n|3", "4|4|5\n5|6"}, nil, "Records: 2 Deleted: 0 Skipped: 0 Warnings: 0"}, } - checkCases(tests, ld, c, tk, ctx, selectSQL, deleteSQL) + checkCases(tests, ld, t, tk, ctx, selectSQL, deleteSQL) ld.LinesInfo.Terminated = "#\n" ld.FieldsInfo.Terminated = "#" @@ -2290,7 +2084,7 @@ func (s *testSuite4) TestLoadData(c *C) { {[]byte("xxx1#2#3#4#\nnxxx2#3#4#5#\n"), nil, []string{"1|2|3|4", "2|3|4|5"}, nil, "Records: 2 Deleted: 0 Skipped: 0 Warnings: 0"}, {[]byte("xxx1#2#\"3#\"#\"4\n\"#\nxxx2#3#\"#4#\n\"#5#\n"), nil, []string{"1|2|3#|4", "2|3|#4#\n|5"}, nil, "Records: 2 Deleted: 0 Skipped: 0 Warnings: 0"}, } - checkCases(tests, ld, c, tk, ctx, selectSQL, deleteSQL) + checkCases(tests, ld, t, tk, ctx, selectSQL, deleteSQL) ld.LinesInfo.Terminated = "#" ld.FieldsInfo.Terminated = "##" @@ -2300,20 +2094,23 @@ func (s *testSuite4) TestLoadData(c *C) { {[]byte("1##2##3##4#2##3##4##5#"), nil, []string{"1|2|3|4", "2|3|4|5"}, nil, "Records: 2 Deleted: 0 Skipped: 0 Warnings: 0"}, {[]byte("1##2##\"3##\"##\"4\n\"#2##3##\"##4#\"##5#"), nil, []string{"1|2|3##|4", "2|3|##4#|5"}, nil, "Records: 2 Deleted: 0 Skipped: 0 Warnings: 0"}, } - checkCases(tests, ld, c, tk, ctx, selectSQL, deleteSQL) + checkCases(tests, ld, t, tk, ctx, selectSQL, deleteSQL) } -func (s *testSuite4) TestLoadDataEscape(c *C) { +func TestLoadDataEscape(t *testing.T) { trivialMsg := "Records: 1 Deleted: 0 Skipped: 0 Warnings: 0" - tk := testkit.NewTestKit(c, s.store) + t.Parallel() + store, clean := testkit.CreateMockStore(t) + defer clean() + tk := testkit.NewTestKit(t, store) tk.MustExec("use test; drop table if exists load_data_test;") tk.MustExec("CREATE TABLE load_data_test (id INT NOT NULL PRIMARY KEY, value TEXT NOT NULL) CHARACTER SET utf8") tk.MustExec("load data local infile '/tmp/nonexistence.csv' into table load_data_test") - ctx := tk.Se.(sessionctx.Context) + ctx := tk.Session().(sessionctx.Context) ld, ok := ctx.Value(executor.LoadDataVarKey).(*executor.LoadDataInfo) - c.Assert(ok, IsTrue) + require.True(t, ok) defer ctx.SetValue(executor.LoadDataVarKey, nil) - c.Assert(ld, NotNil) + require.NotNil(t, ld) // test escape tests := []testCase{ // data1 = nil, data2 != nil @@ -2329,21 +2126,24 @@ func (s *testSuite4) TestLoadDataEscape(c *C) { } deleteSQL := "delete from load_data_test" selectSQL := "select * from load_data_test;" - checkCases(tests, ld, c, tk, ctx, selectSQL, deleteSQL) + checkCases(tests, ld, t, tk, ctx, selectSQL, deleteSQL) } // TestLoadDataSpecifiedColumns reuse TestLoadDataEscape's test case :-) -func (s *testSuite4) TestLoadDataSpecifiedColumns(c *C) { +func TestLoadDataSpecifiedColumns(t *testing.T) { trivialMsg := "Records: 1 Deleted: 0 Skipped: 0 Warnings: 0" - tk := testkit.NewTestKit(c, s.store) + t.Parallel() + store, clean := testkit.CreateMockStore(t) + defer clean() + tk := testkit.NewTestKit(t, store) tk.MustExec("use test; drop table if exists load_data_test;") tk.MustExec(`create table load_data_test (id int PRIMARY KEY AUTO_INCREMENT, c1 int, c2 varchar(255) default "def", c3 int default 0);`) tk.MustExec("load data local infile '/tmp/nonexistence.csv' into table load_data_test (c1, c2)") - ctx := tk.Se.(sessionctx.Context) + ctx := tk.Session().(sessionctx.Context) ld, ok := ctx.Value(executor.LoadDataVarKey).(*executor.LoadDataInfo) - c.Assert(ok, IsTrue) + require.True(t, ok) defer ctx.SetValue(executor.LoadDataVarKey, nil) - c.Assert(ld, NotNil) + require.NotNil(t, ld) // test tests := []testCase{ // data1 = nil, data2 != nil @@ -2357,75 +2157,87 @@ func (s *testSuite4) TestLoadDataSpecifiedColumns(c *C) { } deleteSQL := "delete from load_data_test" selectSQL := "select * from load_data_test;" - checkCases(tests, ld, c, tk, ctx, selectSQL, deleteSQL) + checkCases(tests, ld, t, tk, ctx, selectSQL, deleteSQL) } -func (s *testSuite4) TestLoadDataIgnoreLines(c *C) { - tk := testkit.NewTestKit(c, s.store) +func TestLoadDataIgnoreLines(t *testing.T) { + t.Parallel() + store, clean := testkit.CreateMockStore(t) + defer clean() + tk := testkit.NewTestKit(t, store) tk.MustExec("use test; drop table if exists load_data_test;") tk.MustExec("CREATE TABLE load_data_test (id INT NOT NULL PRIMARY KEY, value TEXT NOT NULL) CHARACTER SET utf8") tk.MustExec("load data local infile '/tmp/nonexistence.csv' into table load_data_test ignore 1 lines") - ctx := tk.Se.(sessionctx.Context) + ctx := tk.Session().(sessionctx.Context) ld, ok := ctx.Value(executor.LoadDataVarKey).(*executor.LoadDataInfo) - c.Assert(ok, IsTrue) + require.True(t, ok) defer ctx.SetValue(executor.LoadDataVarKey, nil) - c.Assert(ld, NotNil) + require.NotNil(t, ld) tests := []testCase{ {nil, []byte("1\tline1\n2\tline2\n"), []string{"2|line2"}, nil, "Records: 1 Deleted: 0 Skipped: 0 Warnings: 0"}, {nil, []byte("1\tline1\n2\tline2\n3\tline3\n"), []string{"2|line2", "3|line3"}, nil, "Records: 2 Deleted: 0 Skipped: 0 Warnings: 0"}, } deleteSQL := "delete from load_data_test" selectSQL := "select * from load_data_test;" - checkCases(tests, ld, c, tk, ctx, selectSQL, deleteSQL) + checkCases(tests, ld, t, tk, ctx, selectSQL, deleteSQL) } // TestLoadDataOverflowBigintUnsigned related to issue 6360 -func (s *testSuite4) TestLoadDataOverflowBigintUnsigned(c *C) { - tk := testkit.NewTestKit(c, s.store) +func TestLoadDataOverflowBigintUnsigned(t *testing.T) { + t.Parallel() + store, clean := testkit.CreateMockStore(t) + defer clean() + tk := testkit.NewTestKit(t, store) tk.MustExec("use test; drop table if exists load_data_test;") tk.MustExec("CREATE TABLE load_data_test (a bigint unsigned);") tk.MustExec("load data local infile '/tmp/nonexistence.csv' into table load_data_test") - ctx := tk.Se.(sessionctx.Context) + ctx := tk.Session().(sessionctx.Context) ld, ok := ctx.Value(executor.LoadDataVarKey).(*executor.LoadDataInfo) - c.Assert(ok, IsTrue) + require.True(t, ok) defer ctx.SetValue(executor.LoadDataVarKey, nil) - c.Assert(ld, NotNil) + require.NotNil(t, ld) tests := []testCase{ {nil, []byte("-1\n-18446744073709551615\n-18446744073709551616\n"), []string{"0", "0", "0"}, nil, "Records: 3 Deleted: 0 Skipped: 0 Warnings: 3"}, {nil, []byte("-9223372036854775809\n18446744073709551616\n"), []string{"0", "18446744073709551615"}, nil, "Records: 2 Deleted: 0 Skipped: 0 Warnings: 2"}, } deleteSQL := "delete from load_data_test" selectSQL := "select * from load_data_test;" - checkCases(tests, ld, c, tk, ctx, selectSQL, deleteSQL) + checkCases(tests, ld, t, tk, ctx, selectSQL, deleteSQL) } -func (s *testSuite4) TestLoadDataIntoPartitionedTable(c *C) { - tk := testkit.NewTestKit(c, s.store) +func TestLoadDataIntoPartitionedTable(t *testing.T) { + t.Parallel() + store, clean := testkit.CreateMockStore(t) + defer clean() + tk := testkit.NewTestKit(t, store) tk.MustExec("use test") tk.MustExec("create table range_t (a int, b int) partition by range (a) ( " + "partition p0 values less than (4)," + "partition p1 values less than (7)," + "partition p2 values less than (11))") tk.MustExec("load data local infile '/tmp/nonexistence.csv' into table range_t fields terminated by ','") - ctx := tk.Se.(sessionctx.Context) + ctx := tk.Session().(sessionctx.Context) ld := ctx.Value(executor.LoadDataVarKey).(*executor.LoadDataInfo) - c.Assert(ctx.NewTxn(context.Background()), IsNil) + require.Nil(t, ctx.NewTxn(context.Background())) _, _, err := ld.InsertData(context.Background(), nil, []byte("1,2\n3,4\n5,6\n7,8\n9,10\n")) - c.Assert(err, IsNil) + require.NoError(t, err) err = ld.CheckAndInsertOneBatch(context.Background(), ld.GetRows(), ld.GetCurBatchCnt()) - c.Assert(err, IsNil) + require.NoError(t, err) ld.SetMaxRowsInBatch(20000) ld.SetMessage() ctx.StmtCommit() txn, err := ctx.Txn(true) - c.Assert(err, IsNil) + require.NoError(t, err) err = txn.Commit(context.Background()) - c.Assert(err, IsNil) + require.NoError(t, err) } -func (s *testSuite4) TestNullDefault(c *C) { - tk := testkit.NewTestKit(c, s.store) +func TestNullDefault(t *testing.T) { + t.Parallel() + store, clean := testkit.CreateMockStore(t) + defer clean() + tk := testkit.NewTestKit(t, store) tk.MustExec("use test; drop table if exists test_null_default;") tk.MustExec("set timestamp = 1234") tk.MustExec("set time_zone = '+08:00'") @@ -2436,8 +2248,11 @@ func (s *testSuite4) TestNullDefault(c *C) { tk.MustQuery("select * from test_null_default").Check(testkit.Rows("", "1970-01-01 08:20:34")) } -func (s *testSuite4) TestNotNullDefault(c *C) { - tk := testkit.NewTestKit(c, s.store) +func TestNotNullDefault(t *testing.T) { + t.Parallel() + store, clean := testkit.CreateMockStore(t) + defer clean() + tk := testkit.NewTestKit(t, store) tk.MustExec("use test; drop table if exists t1,t2;") defer tk.MustExec("drop table t1,t2") tk.MustExec("create table t1 (a int not null default null default 1);") @@ -2445,28 +2260,28 @@ func (s *testSuite4) TestNotNullDefault(c *C) { tk.MustExec("alter table t2 change column a a int not null default null default 1;") } -func (s *testBypassSuite) TestLatch(c *C) { +func TestLatch(t *testing.T) { store, err := mockstore.NewMockStore( // Small latch slot size to make conflicts. mockstore.WithTxnLocalLatches(64), ) - c.Assert(err, IsNil) + require.NoError(t, err) defer func() { err := store.Close() - c.Assert(err, IsNil) + require.NoError(t, err) }() dom, err1 := session.BootstrapSession(store) - c.Assert(err1, IsNil) + require.Nil(t, err1) defer dom.Close() - tk1 := testkit.NewTestKit(c, store) + tk1 := testkit.NewTestKit(t, store) tk1.MustExec("use test") tk1.MustExec("drop table if exists t") tk1.MustExec("create table t (id int)") tk1.MustExec("set @@tidb_disable_txn_auto_retry = true") - tk2 := testkit.NewTestKit(c, store) + tk2 := testkit.NewTestKit(t, store) tk2.MustExec("use test") tk1.MustExec("set @@tidb_disable_txn_auto_retry = true") @@ -2496,7 +2311,7 @@ func (s *testBypassSuite) TestLatch(c *C) { tk1.MustExec("update t set id = id + 1") tk2.MustExec("update t set id = id + 1") _, err = tk1.Exec("commit") - c.Assert(kv.ErrWriteConflictInTiDB.Equal(err), IsTrue) + require.True(t, kv.ErrWriteConflictInTiDB.Equal(err)) tk1.MustExec("set @@tidb_disable_txn_auto_retry = 0") tk1.MustExec("update t set id = id + 1") @@ -2505,8 +2320,11 @@ func (s *testBypassSuite) TestLatch(c *C) { } // TestIssue4067 Test issue https://github.com/pingcap/tidb/issues/4067 -func (s *testSuite7) TestIssue4067(c *C) { - tk := testkit.NewTestKit(c, s.store) +func TestIssue4067(t *testing.T) { + t.Parallel() + store, clean := testkit.CreateMockStore(t) + defer clean() + tk := testkit.NewTestKit(t, store) tk.MustExec("use test") tk.MustExec("drop table if exists t1, t2") tk.MustExec("create table t1(id int)") @@ -2519,8 +2337,11 @@ func (s *testSuite7) TestIssue4067(c *C) { tk.MustQuery("select * from t1").Check(nil) } -func (s *testSuite7) TestInsertCalculatedValue(c *C) { - tk := testkit.NewTestKit(c, s.store) +func TestInsertCalculatedValue(t *testing.T) { + t.Parallel() + store, clean := testkit.CreateMockStore(t) + defer clean() + tk := testkit.NewTestKit(t, store) tk.MustExec("use test") tk.MustExec("drop table if exists t") @@ -2635,44 +2456,53 @@ func (s *testSuite7) TestInsertCalculatedValue(c *C) { tk.MustQuery("select * from t").Check(testkit.Rows("4 0 2")) } -func (s *testSuite7) TestDataTooLongErrMsg(c *C) { - tk := testkit.NewTestKit(c, s.store) +func TestDataTooLongErrMsg(t *testing.T) { + t.Parallel() + store, clean := testkit.CreateMockStore(t) + defer clean() + tk := testkit.NewTestKit(t, store) tk.MustExec("use test") tk.MustExec("create table t(a varchar(2));") _, err := tk.Exec("insert into t values('123');") - c.Assert(types.ErrDataTooLong.Equal(err), IsTrue) - c.Assert(err.Error(), Equals, "[types:1406]Data too long for column 'a' at row 1") + require.True(t, types.ErrDataTooLong.Equal(err)) + require.EqualError(t, err, "[types:1406]Data too long for column 'a' at row 1") tk.MustExec("insert into t values('12')") _, err = tk.Exec("update t set a = '123' where a = '12';") - c.Assert(types.ErrDataTooLong.Equal(err), IsTrue) - c.Assert(err.Error(), Equals, "[types:1406]Data too long for column 'a' at row 1") + require.True(t, types.ErrDataTooLong.Equal(err)) + require.EqualError(t, err, "[types:1406]Data too long for column 'a' at row 1") } -func (s *testSuite7) TestUpdateSelect(c *C) { - tk := testkit.NewTestKit(c, s.store) +func TestUpdateSelect(t *testing.T) { + t.Parallel() + store, clean := testkit.CreateMockStore(t) + defer clean() + tk := testkit.NewTestKit(t, store) tk.MustExec("use test") tk.MustExec("create table msg (id varchar(8), b int, status int, primary key (id, b))") tk.MustExec("insert msg values ('abc', 1, 1)") tk.MustExec("create table detail (id varchar(8), start varchar(8), status int, index idx_start(start))") tk.MustExec("insert detail values ('abc', '123', 2)") tk.MustExec("UPDATE msg SET msg.status = (SELECT detail.status FROM detail WHERE msg.id = detail.id)") - tk.CheckLastMessage("Rows matched: 1 Changed: 1 Warnings: 0") + require.Equal(t, tk.Session().LastMessage(), "Rows matched: 1 Changed: 1 Warnings: 0") tk.MustExec("admin check table msg") } -func (s *testSuite7) TestUpdateDelete(c *C) { - tk := testkit.NewTestKit(c, s.store) +func TestUpdateDelete(t *testing.T) { + t.Parallel() + store, clean := testkit.CreateMockStore(t) + defer clean() + tk := testkit.NewTestKit(t, store) tk.MustExec("use test") tk.MustExec("CREATE TABLE ttt (id bigint(20) NOT NULL, host varchar(30) NOT NULL, PRIMARY KEY (id), UNIQUE KEY i_host (host));") tk.MustExec("insert into ttt values (8,8),(9,9);") tk.MustExec("begin") tk.MustExec("update ttt set id = 0, host='9' where id = 9 limit 1;") - tk.CheckLastMessage("Rows matched: 1 Changed: 1 Warnings: 0") + require.Equal(t, tk.Session().LastMessage(), "Rows matched: 1 Changed: 1 Warnings: 0") tk.MustExec("delete from ttt where id = 0 limit 1;") tk.MustQuery("select * from ttt use index (i_host) order by host;").Check(testkit.Rows("8 8")) tk.MustExec("update ttt set id = 0, host='8' where id = 8 limit 1;") - tk.CheckLastMessage("Rows matched: 1 Changed: 1 Warnings: 0") + require.Equal(t, tk.Session().LastMessage(), "Rows matched: 1 Changed: 1 Warnings: 0") tk.MustExec("delete from ttt where id = 0 limit 1;") tk.MustQuery("select * from ttt use index (i_host) order by host;").Check(testkit.Rows()) tk.MustExec("commit") @@ -2680,78 +2510,85 @@ func (s *testSuite7) TestUpdateDelete(c *C) { tk.MustExec("drop table ttt") } -func (s *testSuite7) TestUpdateAffectRowCnt(c *C) { - tk := testkit.NewTestKit(c, s.store) +func TestUpdateAffectRowCnt(t *testing.T) { + t.Parallel() + store, clean := testkit.CreateMockStore(t) + defer clean() + tk := testkit.NewTestKit(t, store) tk.MustExec("use test") tk.MustExec("create table a(id int auto_increment, a int default null, primary key(id))") tk.MustExec("insert into a values (1, 1001), (2, 1001), (10001, 1), (3, 1)") tk.MustExec("update a set id = id*10 where a = 1001") - ctx := tk.Se.(sessionctx.Context) - c.Assert(ctx.GetSessionVars().StmtCtx.AffectedRows(), Equals, uint64(2)) - tk.CheckLastMessage("Rows matched: 2 Changed: 2 Warnings: 0") + ctx := tk.Session().(sessionctx.Context) + require.Equal(t, uint64(2), ctx.GetSessionVars().StmtCtx.AffectedRows()) + require.Equal(t, tk.Session().LastMessage(), "Rows matched: 2 Changed: 2 Warnings: 0") tk.MustExec("drop table a") tk.MustExec("create table a ( a bigint, b bigint)") tk.MustExec("insert into a values (1, 1001), (2, 1001), (10001, 1), (3, 1)") tk.MustExec("update a set a = a*10 where b = 1001") - ctx = tk.Se.(sessionctx.Context) - c.Assert(ctx.GetSessionVars().StmtCtx.AffectedRows(), Equals, uint64(2)) - tk.CheckLastMessage("Rows matched: 2 Changed: 2 Warnings: 0") + ctx = tk.Session().(sessionctx.Context) + require.Equal(t, uint64(2), ctx.GetSessionVars().StmtCtx.AffectedRows()) + require.Equal(t, tk.Session().LastMessage(), "Rows matched: 2 Changed: 2 Warnings: 0") } -func (s *testSuite7) TestReplaceLog(c *C) { - tk := testkit.NewTestKit(c, s.store) +func TestReplaceLog(t *testing.T) { + t.Parallel() + store, domain, clean := testkit.CreateMockStoreAndDomain(t) + defer clean() + tk := testkit.NewTestKit(t, store) tk.MustExec("use test") tk.MustExec(`create table testLog (a int not null primary key, b int unique key);`) // Make some dangling index. - s.ctx = mock.NewContext() - s.ctx.Store = s.store - is := s.domain.InfoSchema() + ctx := mock.NewContext() + ctx.Store = store + is := domain.InfoSchema() dbName := model.NewCIStr("test") tblName := model.NewCIStr("testLog") tbl, err := is.TableByName(dbName, tblName) - c.Assert(err, IsNil) + require.NoError(t, err) tblInfo := tbl.Meta() idxInfo := tblInfo.FindIndexByName("b") indexOpr := tables.NewIndex(tblInfo.ID, tblInfo, idxInfo) - txn, err := s.store.Begin() - c.Assert(err, IsNil) - _, err = indexOpr.Create(s.ctx, txn, types.MakeDatums(1), kv.IntHandle(1), nil) - c.Assert(err, IsNil) + txn, err := store.Begin() + require.NoError(t, err) + _, err = indexOpr.Create(ctx, txn, types.MakeDatums(1), kv.IntHandle(1), nil) + require.NoError(t, err) err = txn.Commit(context.Background()) - c.Assert(err, IsNil) + require.NoError(t, err) _, err = tk.Exec(`replace into testLog values (0, 0), (1, 1);`) - c.Assert(err, NotNil) - expErr := errors.New(`can not be duplicated row, due to old row not found. handle 1 not found`) - c.Assert(expErr.Error() == err.Error(), IsTrue, Commentf("obtained error: (%s)\nexpected error: (%s)", err.Error(), expErr.Error())) - + require.Error(t, err) + require.EqualError(t, err, `can not be duplicated row, due to old row not found. handle 1 not found`) tk.MustQuery(`admin cleanup index testLog b;`).Check(testkit.Rows("1")) } // TestRebaseIfNeeded is for issue 7422. // There is no need to do the rebase when updating a record if the auto-increment ID not changed. // This could make the auto ID increasing speed slower. -func (s *testSuite7) TestRebaseIfNeeded(c *C) { - tk := testkit.NewTestKit(c, s.store) +func TestRebaseIfNeeded(t *testing.T) { + t.Parallel() + store, domain, clean := testkit.CreateMockStoreAndDomain(t) + defer clean() + tk := testkit.NewTestKit(t, store) tk.MustExec("use test") tk.MustExec(`create table t (a int not null primary key auto_increment, b int unique key);`) tk.MustExec(`insert into t (b) values (1);`) - s.ctx = mock.NewContext() - s.ctx.Store = s.store - tbl, err := s.domain.InfoSchema().TableByName(model.NewCIStr("test"), model.NewCIStr("t")) - c.Assert(err, IsNil) - c.Assert(s.ctx.NewTxn(context.Background()), IsNil) + ctx := mock.NewContext() + ctx.Store = store + tbl, err := domain.InfoSchema().TableByName(model.NewCIStr("test"), model.NewCIStr("t")) + require.NoError(t, err) + require.Nil(t, ctx.NewTxn(context.Background())) // AddRecord directly here will skip to rebase the auto ID in the insert statement, // which could simulate another TiDB adds a large auto ID. - _, err = tbl.AddRecord(s.ctx, types.MakeDatums(30001, 2)) - c.Assert(err, IsNil) - txn, err := s.ctx.Txn(true) - c.Assert(err, IsNil) - c.Assert(txn.Commit(context.Background()), IsNil) + _, err = tbl.AddRecord(ctx, types.MakeDatums(30001, 2)) + require.NoError(t, err) + txn, err := ctx.Txn(true) + require.NoError(t, err) + require.Nil(t, txn.Commit(context.Background())) tk.MustExec(`update t set b = 3 where a = 30001;`) tk.MustExec(`insert into t (b) values (4);`) @@ -2766,8 +2603,11 @@ func (s *testSuite7) TestRebaseIfNeeded(c *C) { tk.MustQuery(`select a from t where b = 6;`).Check(testkit.Rows("30003")) } -func (s *testSuite7) TestDeferConstraintCheckForDelete(c *C) { - tk := testkit.NewTestKit(c, s.store) +func TestDeferConstraintCheckForDelete(t *testing.T) { + t.Parallel() + store, clean := testkit.CreateMockStore(t) + defer clean() + tk := testkit.NewTestKit(t, store) tk.MustExec("set tidb_constraint_check_in_place = 0") tk.MustExec("set @@tidb_txn_mode = 'optimistic'") tk.MustExec("use test") @@ -2779,7 +2619,7 @@ func (s *testSuite7) TestDeferConstraintCheckForDelete(c *C) { tk.MustExec("insert into t1 values(1, 3)") tk.MustExec("delete from t1 where j = 3") _, err := tk.Exec("commit") - c.Assert(err.Error(), Equals, "previous statement: delete from t1 where j = 3: [kv:1062]Duplicate entry '1' for key 'PRIMARY'") + require.EqualError(t, err, "previous statement: delete from t1 where j = 3: [kv:1062]Duplicate entry '1' for key 'PRIMARY'") tk.MustExec("rollback") tk.MustExec("create table t2(i int, j int, unique index idx(i))") @@ -2788,7 +2628,7 @@ func (s *testSuite7) TestDeferConstraintCheckForDelete(c *C) { tk.MustExec("insert into t2 values(1, 3)") tk.MustExec("delete from t2 where j = 3") _, err = tk.Exec("commit") - c.Assert(err.Error(), Equals, "previous statement: delete from t2 where j = 3: [kv:1062]Duplicate entry '1' for key 'idx'") + require.EqualError(t, err, "previous statement: delete from t2 where j = 3: [kv:1062]Duplicate entry '1' for key 'idx'") tk.MustExec("admin check table t2") tk.MustExec("create table t3(i int, j int, primary key(i))") @@ -2816,21 +2656,24 @@ func (s *testSuite7) TestDeferConstraintCheckForDelete(c *C) { tk.MustQuery("select * from t5").Check(testkit.Rows("1 4")) } -func (s *testSuite7) TestDeferConstraintCheckForInsert(c *C) { - tk := testkit.NewTestKit(c, s.store) +func TestDeferConstraintCheckForInsert(t *testing.T) { + t.Parallel() + store, clean := testkit.CreateMockStore(t) + defer clean() + tk := testkit.NewTestKit(t, store) tk.MustExec(`use test`) tk.MustExec(`drop table if exists t;create table t (a int primary key, b int);`) tk.MustExec(`insert into t values (1,2),(2,2)`) _, err := tk.Exec("update t set a=a+1 where b=2") - c.Assert(err, NotNil) + require.Error(t, err) tk.MustExec(`drop table if exists t;create table t (i int key);`) tk.MustExec(`insert t values (1);`) tk.MustExec(`set tidb_constraint_check_in_place = 1;`) tk.MustExec(`begin;`) _, err = tk.Exec(`insert t values (1);`) - c.Assert(err, NotNil) + require.Error(t, err) tk.MustExec(`update t set i = 2 where i = 1;`) tk.MustExec(`commit;`) tk.MustQuery(`select * from t;`).Check(testkit.Rows("2")) @@ -2839,9 +2682,9 @@ func (s *testSuite7) TestDeferConstraintCheckForInsert(c *C) { tk.MustExec("replace into t values (1),(2)") tk.MustExec("begin") _, err = tk.Exec("update t set i = 2 where i = 1") - c.Assert(err, NotNil) + require.Error(t, err) _, err = tk.Exec("insert into t values (1) on duplicate key update i = i + 1") - c.Assert(err, NotNil) + require.Error(t, err) tk.MustExec("rollback") tk.MustExec(`drop table t; create table t (id int primary key, v int unique);`) @@ -2850,16 +2693,16 @@ func (s *testSuite7) TestDeferConstraintCheckForInsert(c *C) { tk.MustExec(`set @@autocommit = 0;`) _, err = tk.Exec("insert into t values (3, 1)") - c.Assert(err, NotNil) + require.Error(t, err) _, err = tk.Exec("insert into t values (1, 3)") - c.Assert(err, NotNil) + require.Error(t, err) tk.MustExec("commit") tk.MustExec(`set tidb_constraint_check_in_place = 0;`) tk.MustExec("insert into t values (3, 1)") tk.MustExec("insert into t values (1, 3)") _, err = tk.Exec("commit") - c.Assert(err, NotNil) + require.Error(t, err) // Cover the temporary table. for val := range []int{0, 1} { @@ -2870,12 +2713,12 @@ func (s *testSuite7) TestDeferConstraintCheckForInsert(c *C) { tk.MustExec("begin") tk.MustExec("insert into t values (1, 1)") _, err = tk.Exec(`insert into t values (1, 3)`) - c.Assert(err, NotNil) + require.Error(t, err) tk.MustExec("insert into t values (2, 2)") _, err = tk.Exec("update t set a = a + 1 where a = 1") - c.Assert(err, NotNil) + require.Error(t, err) _, err = tk.Exec("insert into t values (1, 3) on duplicated key update a = a + 1") - c.Assert(err, NotNil) + require.Error(t, err) tk.MustExec("commit") tk.MustExec("drop table t") @@ -2883,12 +2726,12 @@ func (s *testSuite7) TestDeferConstraintCheckForInsert(c *C) { tk.MustExec("begin") tk.MustExec("insert into t values (1, 1)") _, err = tk.Exec(`insert into t values (3, 1)`) - c.Assert(err, NotNil) + require.Error(t, err) tk.MustExec("insert into t values (2, 2)") _, err = tk.Exec("update t set b = b + 1 where a = 1") - c.Assert(err, NotNil) + require.Error(t, err) _, err = tk.Exec("insert into t values (3, 1) on duplicated key update b = b + 1") - c.Assert(err, NotNil) + require.Error(t, err) tk.MustExec("commit") // cases for temporary table @@ -2897,22 +2740,22 @@ func (s *testSuite7) TestDeferConstraintCheckForInsert(c *C) { tk.MustExec("begin") tk.MustExec("insert into tl values (1, 1)") _, err = tk.Exec(`insert into tl values (1, 3)`) - c.Assert(err, NotNil) + require.Error(t, err) tk.MustExec("insert into tl values (2, 2)") _, err = tk.Exec("update tl set a = a + 1 where a = 1") - c.Assert(err, NotNil) + require.Error(t, err) _, err = tk.Exec("insert into tl values (1, 3) on duplicated key update a = a + 1") - c.Assert(err, NotNil) + require.Error(t, err) tk.MustExec("commit") tk.MustExec("begin") tk.MustQuery("select * from tl").Check(testkit.Rows("1 1", "2 2")) _, err = tk.Exec(`insert into tl values (1, 3)`) - c.Assert(err, NotNil) + require.Error(t, err) _, err = tk.Exec("update tl set a = a + 1 where a = 1") - c.Assert(err, NotNil) + require.Error(t, err) _, err = tk.Exec("insert into tl values (1, 3) on duplicated key update a = a + 1") - c.Assert(err, NotNil) + require.Error(t, err) tk.MustExec("rollback") tk.MustExec("drop table tl") @@ -2920,29 +2763,35 @@ func (s *testSuite7) TestDeferConstraintCheckForInsert(c *C) { tk.MustExec("begin") tk.MustExec("insert into tl values (1, 1)") _, err = tk.Exec(`insert into tl values (3, 1)`) - c.Assert(err, NotNil) + require.Error(t, err) tk.MustExec("insert into tl values (2, 2)") _, err = tk.Exec("update tl set b = b + 1 where a = 1") - c.Assert(err, NotNil) + require.Error(t, err) _, err = tk.Exec("insert into tl values (3, 1) on duplicated key update b = b + 1") - c.Assert(err, NotNil) + require.Error(t, err) tk.MustExec("commit") tk.MustExec("begin") tk.MustQuery("select * from tl").Check(testkit.Rows("1 1", "2 2")) _, err = tk.Exec(`insert into tl values (3, 1)`) - c.Assert(err, NotNil) + require.Error(t, err) _, err = tk.Exec("update tl set b = b + 1 where a = 1") - c.Assert(err, NotNil) + require.Error(t, err) _, err = tk.Exec("insert into tl values (3, 1) on duplicated key update b = b + 1") - c.Assert(err, NotNil) + require.Error(t, err) tk.MustExec("rollback") } } -func (s *testSuite7) TestPessimisticDeleteYourWrites(c *C) { - session1 := testkit.NewTestKitWithInit(c, s.store) - session2 := testkit.NewTestKitWithInit(c, s.store) +func TestPessimisticDeleteYourWrites(t *testing.T) { + t.Parallel() + store, clean := testkit.CreateMockStore(t) + defer clean() + + session1 := testkit.NewTestKit(t, store) + session1.MustExec("use test") + session2 := testkit.NewTestKit(t, store) + session2.MustExec("use test") session1.MustExec("drop table if exists x;") session1.MustExec("create table x (id int primary key, c int);") @@ -2954,37 +2803,45 @@ func (s *testSuite7) TestPessimisticDeleteYourWrites(c *C) { session1.MustExec("insert into x select 1, 1") session1.MustExec("delete from x where id = 1") session2.MustExec("begin;") - var wg sync.WaitGroup - wg.Add(1) - go func() { + var wg util.WaitGroupWrapper + wg.Run(func() { session2.MustExec("insert into x select 1, 2") - wg.Done() - }() + }) session1.MustExec("commit;") wg.Wait() session2.MustExec("commit;") session2.MustQuery("select * from x").Check(testkit.Rows("1 2")) } -func (s *testSuite7) TestDefEnumInsert(c *C) { - tk := testkit.NewTestKit(c, s.store) +func TestDefEnumInsert(t *testing.T) { + t.Parallel() + store, clean := testkit.CreateMockStore(t) + defer clean() + tk := testkit.NewTestKit(t, store) tk.MustExec("use test") tk.MustExec("create table test (id int, prescription_type enum('a','b','c','d','e','f') NOT NULL, primary key(id));") tk.MustExec("insert into test (id) values (1)") tk.MustQuery("select prescription_type from test").Check(testkit.Rows("a")) } -func (s *testSuite7) TestIssue11059(c *C) { - tk := testkit.NewTestKitWithInit(c, s.store) +func TestIssue11059(t *testing.T) { + t.Parallel() + store, clean := testkit.CreateMockStore(t) + defer clean() + tk := testkit.NewTestKit(t, store) + tk.MustExec("use test") tk.MustExec("create table t (pk int primary key, uk int unique, v int)") tk.MustExec("insert into t values (2, 11, 215)") tk.MustExec("insert into t values (3, 7, 2111)") _, err := tk.Exec("update t set pk = 2 where uk = 7") - c.Assert(err, NotNil) + require.Error(t, err) } -func (s *testSuite7) TestSetWithRefGenCol(c *C) { - tk := testkit.NewTestKitWithInit(c, s.store) +func TestSetWithRefGenCol(t *testing.T) { + t.Parallel() + store, clean := testkit.CreateMockStore(t) + defer clean() + tk := testkit.NewTestKit(t, store) tk.MustExec("use test") tk.MustExec(`create table t (i int, j int as (i+1) not null);`) tk.MustExec(`insert into t set i = j + 1;`) @@ -3015,7 +2872,7 @@ func (s *testSuite7) TestSetWithRefGenCol(c *C) { tk.MustExec(`insert into t2 set i = j + 9`) tk.MustQuery("select * from t2").Check(testkit.Rows("10 9")) _, err := tk.Exec(`insert into t2 set j = i + 1`) - c.Assert(err, NotNil) + require.Error(t, err) tk.MustExec(`insert into t2 set i = j + 100`) tk.MustQuery("select * from t2").Check(testkit.Rows("10 9", "101 100")) @@ -3023,11 +2880,14 @@ func (s *testSuite7) TestSetWithRefGenCol(c *C) { tk.MustExec(`insert into t3 set i = j + 100`) tk.MustQuery("select * from t3").Check(testkit.Rows(" ")) _, err = tk.Exec(`insert into t3 set j = i + 1`) - c.Assert(err, NotNil) + require.Error(t, err) } -func (s *testSuite7) TestSetWithCurrentTimestampAndNow(c *C) { - tk := testkit.NewTestKitWithInit(c, s.store) +func TestSetWithCurrentTimestampAndNow(t *testing.T) { + t.Parallel() + store, clean := testkit.CreateMockStore(t) + defer clean() + tk := testkit.NewTestKit(t, store) tk.MustExec("use test") tk.MustExec(`drop table if exists tbl;`) tk.MustExec(`create table t1(c1 timestamp default current_timestamp, c2 int, c3 timestamp default current_timestamp);`) @@ -3038,8 +2898,11 @@ func (s *testSuite7) TestSetWithCurrentTimestampAndNow(c *C) { tk.MustQuery("select c1 = c3 from t1").Check(testkit.Rows("1", "1")) } -func (s *testSuite7) TestApplyWithPointAndBatchPointGet(c *C) { - tk := testkit.NewTestKitWithInit(c, s.store) +func TestApplyWithPointAndBatchPointGet(t *testing.T) { + t.Parallel() + store, clean := testkit.CreateMockStore(t) + defer clean() + tk := testkit.NewTestKit(t, store) tk.MustExec("use test") tk.MustExec(`drop table if exists t;`) tk.MustExec(`create table t ( c_int int, c_str varchar(40),c_datetime datetime, c_timestamp timestamp, @@ -3079,8 +2942,11 @@ from t order by c_str;`).Check(testkit.Rows("10")) from t order by c_str;`).Check(testkit.Rows("10")) } -func (s *testSuite4) TestWriteListPartitionTable(c *C) { - tk := testkit.NewTestKitWithInit(c, s.store) +func TestWriteListPartitionTable(t *testing.T) { + t.Parallel() + store, clean := testkit.CreateMockStore(t) + defer clean() + tk := testkit.NewTestKit(t, store) tk.MustExec("use test") tk.MustExec("set @@session.tidb_enable_list_partition = ON") tk.MustExec("drop table if exists t") @@ -3110,9 +2976,9 @@ func (s *testSuite4) TestWriteListPartitionTable(c *C) { // Test insert error tk.MustExec("insert into t values (1, 'a')") _, err := tk.Exec("insert into t values (1, 'd')") - c.Assert(err.Error(), Equals, "[kv:1062]Duplicate entry '1' for key 'idx'") + require.EqualError(t, err, "[kv:1062]Duplicate entry '1' for key 'idx'") _, err = tk.Exec("insert into t values (100, 'd')") - c.Assert(err.Error(), Equals, "[table:1526]Table has no partition for value 100") + require.EqualError(t, err, "[table:1526]Table has no partition for value 100") tk.MustExec("admin check table t;") // Test select partition @@ -3127,8 +2993,11 @@ func (s *testSuite4) TestWriteListPartitionTable(c *C) { tk.MustQuery("select * from t order by id").Check(testkit.Rows("1 a", "2 b")) } -func (s *testSuite4) TestWriteListColumnsPartitionTable(c *C) { - tk := testkit.NewTestKitWithInit(c, s.store) +func TestWriteListColumnsPartitionTable(t *testing.T) { + t.Parallel() + store, clean := testkit.CreateMockStore(t) + defer clean() + tk := testkit.NewTestKit(t, store) tk.MustExec("use test") tk.MustExec("set @@session.tidb_enable_list_partition = ON") tk.MustExec("drop table if exists t") @@ -3158,9 +3027,9 @@ func (s *testSuite4) TestWriteListColumnsPartitionTable(c *C) { // Test insert error tk.MustExec("insert into t values (1, 'a')") _, err := tk.Exec("insert into t values (1, 'd')") - c.Assert(err.Error(), Equals, "[kv:1062]Duplicate entry '1' for key 'idx'") + require.EqualError(t, err, "[kv:1062]Duplicate entry '1' for key 'idx'") _, err = tk.Exec("insert into t values (100, 'd')") - c.Assert(err.Error(), Equals, "[table:1526]Table has no partition for value from column_list") + require.EqualError(t, err, "[table:1526]Table has no partition for value from column_list") tk.MustExec("admin check table t;") // Test select partition @@ -3176,8 +3045,11 @@ func (s *testSuite4) TestWriteListColumnsPartitionTable(c *C) { } // TestWriteListPartitionTable1 test for write list partition when the partition expression is simple. -func (s *testSuite4) TestWriteListPartitionTable1(c *C) { - tk := testkit.NewTestKitWithInit(c, s.store) +func TestWriteListPartitionTable1(t *testing.T) { + t.Parallel() + store, clean := testkit.CreateMockStore(t) + defer clean() + tk := testkit.NewTestKit(t, store) tk.MustExec("use test") tk.MustExec("set @@session.tidb_enable_list_partition = ON") tk.MustExec("drop table if exists t") @@ -3191,7 +3063,7 @@ func (s *testSuite4) TestWriteListPartitionTable1(c *C) { // Test add unique index failed. tk.MustExec("insert into t values (1, 'a'),(1,'b')") _, err := tk.Exec("alter table t add unique index idx (id)") - c.Assert(err.Error(), Equals, "[kv:1062]Duplicate entry '1' for key 'idx'") + require.EqualError(t, err, "[kv:1062]Duplicate entry '1' for key 'idx'") // Test add unique index success. tk.MustExec("delete from t where name='b'") tk.MustExec("alter table t add unique index idx (id)") @@ -3216,7 +3088,7 @@ func (s *testSuite4) TestWriteListPartitionTable1(c *C) { tk.MustQuery("select * from t partition(p3) order by id").Check(testkit.Rows()) // Test insert on duplicate error _, err = tk.Exec("insert into t values (3, 'a'), (11,'x') on duplicate key update id=id+1") - c.Assert(err.Error(), Equals, "[kv:1062]Duplicate entry '4' for key 'idx'") + require.EqualError(t, err, "[kv:1062]Duplicate entry '4' for key 'idx'") tk.MustQuery("select * from t order by id").Check(testkit.Rows("1 x", "3 x", "4 e", "5 g")) // Test insert ignore with duplicate tk.MustExec("insert ignore into t values (1, 'b'), (5,'a'),(null,'y')") @@ -3231,7 +3103,7 @@ func (s *testSuite4) TestWriteListPartitionTable1(c *C) { tk.MustQuery("select * from t partition(p3) order by id").Check(testkit.Rows(" y", "15 a")) // Test insert meet no partition error. _, err = tk.Exec("insert into t values (100, 'd')") - c.Assert(err.Error(), Equals, "[table:1526]Table has no partition for value 100") + require.EqualError(t, err, "[table:1526]Table has no partition for value 100") // --------------------------Test update--------------------------- // Test update 1 partition. @@ -3245,7 +3117,7 @@ func (s *testSuite4) TestWriteListPartitionTable1(c *C) { tk.MustQuery("select * from t order by id").Check(testkit.Rows("1 y", "2 y", "3 c")) // Test update meet duplicate error. _, err = tk.Exec("update t set id=2 where id = 1") - c.Assert(err.Error(), Equals, "[kv:1062]Duplicate entry '2' for key 'idx'") + require.EqualError(t, err, "[kv:1062]Duplicate entry '2' for key 'idx'") tk.MustQuery("select * from t order by id").Check(testkit.Rows("1 y", "2 y", "3 c")) // Test update multi-partitions @@ -3257,11 +3129,11 @@ func (s *testSuite4) TestWriteListPartitionTable1(c *C) { tk.MustQuery("select * from t order by id").Check(testkit.Rows("3 a", "10 a", "20 a")) // Test update meet duplicate error. _, err = tk.Exec("update t set id=id+17 where id in (3,10)") - c.Assert(err.Error(), Equals, "[kv:1062]Duplicate entry '20' for key 'idx'") + require.EqualError(t, err, "[kv:1062]Duplicate entry '20' for key 'idx'") tk.MustQuery("select * from t order by id").Check(testkit.Rows("3 a", "10 a", "20 a")) // Test update meet no partition error. _, err = tk.Exec("update t set id=id*2 where id in (3,20)") - c.Assert(err.Error(), Equals, "[table:1526]Table has no partition for value 40") + require.EqualError(t, err, "[table:1526]Table has no partition for value 40") tk.MustQuery("select * from t order by id").Check(testkit.Rows("3 a", "10 a", "20 a")) // --------------------------Test replace--------------------------- @@ -3280,7 +3152,7 @@ func (s *testSuite4) TestWriteListPartitionTable1(c *C) { tk.MustQuery("select * from t order by id").Check(testkit.Rows("1 x", "2 b", "3 c", "4 d", "7 x")) // Test replace meet no partition error. _, err = tk.Exec("replace into t values (10,'x'),(50,'x')") - c.Assert(err.Error(), Equals, "[table:1526]Table has no partition for value 50") + require.EqualError(t, err, "[table:1526]Table has no partition for value 50") tk.MustQuery("select * from t order by id").Check(testkit.Rows("1 x", "2 b", "3 c", "4 d", "7 x")) // --------------------------Test delete--------------------------- @@ -3301,8 +3173,11 @@ func (s *testSuite4) TestWriteListPartitionTable1(c *C) { } // TestWriteListPartitionTable2 test for write list partition when the partition expression is complicated and contain generated column. -func (s *testSuite4) TestWriteListPartitionTable2(c *C) { - tk := testkit.NewTestKitWithInit(c, s.store) +func TestWriteListPartitionTable2(t *testing.T) { + t.Parallel() + store, clean := testkit.CreateMockStore(t) + defer clean() + tk := testkit.NewTestKit(t, store) tk.MustExec("use test") tk.MustExec("set @@session.tidb_enable_list_partition = ON") tk.MustExec("drop table if exists t") @@ -3317,7 +3192,7 @@ func (s *testSuite4) TestWriteListPartitionTable2(c *C) { // Test add unique index failed. tk.MustExec("insert into t (id,name) values (1, 'a'),(1,'b')") _, err := tk.Exec("alter table t add unique index idx (id,b)") - c.Assert(err.Error(), Equals, "[kv:1062]Duplicate entry '1-2' for key 'idx'") + require.EqualError(t, err, "[kv:1062]Duplicate entry '1-2' for key 'idx'") // Test add unique index success. tk.MustExec("delete from t where name='b'") tk.MustExec("alter table t add unique index idx (id,b)") @@ -3342,7 +3217,7 @@ func (s *testSuite4) TestWriteListPartitionTable2(c *C) { tk.MustQuery("select id,name from t partition(p3) order by id").Check(testkit.Rows()) // Test insert on duplicate error _, err = tk.Exec("insert into t (id,name) values (3, 'a'), (11,'x') on duplicate key update id=id+1") - c.Assert(err.Error(), Equals, "[kv:1062]Duplicate entry '4-2' for key 'idx'") + require.EqualError(t, err, "[kv:1062]Duplicate entry '4-2' for key 'idx'") tk.MustQuery("select id,name from t order by id").Check(testkit.Rows("1 x", "3 x", "4 e", "5 g")) // Test insert ignore with duplicate tk.MustExec("insert ignore into t (id,name) values (1, 'b'), (5,'a'),(null,'y')") @@ -3357,7 +3232,7 @@ func (s *testSuite4) TestWriteListPartitionTable2(c *C) { tk.MustQuery("select id,name from t partition(p3) order by id").Check(testkit.Rows(" y", "15 a")) // Test insert meet no partition error. _, err = tk.Exec("insert into t (id,name) values (100, 'd')") - c.Assert(err.Error(), Equals, "[table:1526]Table has no partition for value 100") + require.EqualError(t, err, "[table:1526]Table has no partition for value 100") // --------------------------Test update--------------------------- // Test update 1 partition. @@ -3371,7 +3246,7 @@ func (s *testSuite4) TestWriteListPartitionTable2(c *C) { tk.MustQuery("select id,name from t order by id").Check(testkit.Rows("1 y", "2 y", "3 c")) // Test update meet duplicate error. _, err = tk.Exec("update t set id=2 where id = 1") - c.Assert(err.Error(), Equals, "[kv:1062]Duplicate entry '2-2' for key 'idx'") + require.EqualError(t, err, "[kv:1062]Duplicate entry '2-2' for key 'idx'") tk.MustQuery("select id,name from t order by id").Check(testkit.Rows("1 y", "2 y", "3 c")) // Test update multi-partitions @@ -3383,11 +3258,11 @@ func (s *testSuite4) TestWriteListPartitionTable2(c *C) { tk.MustQuery("select id,name from t order by id").Check(testkit.Rows("3 a", "10 a", "20 a")) // Test update meet duplicate error. _, err = tk.Exec("update t set id=id+17 where id in (3,10)") - c.Assert(err.Error(), Equals, "[kv:1062]Duplicate entry '20-2' for key 'idx'") + require.EqualError(t, err, "[kv:1062]Duplicate entry '20-2' for key 'idx'") tk.MustQuery("select id,name from t order by id").Check(testkit.Rows("3 a", "10 a", "20 a")) // Test update meet no partition error. _, err = tk.Exec("update t set id=id*2 where id in (3,20)") - c.Assert(err.Error(), Equals, "[table:1526]Table has no partition for value 40") + require.EqualError(t, err, "[table:1526]Table has no partition for value 40") tk.MustQuery("select id,name from t order by id").Check(testkit.Rows("3 a", "10 a", "20 a")) // --------------------------Test replace--------------------------- @@ -3406,7 +3281,7 @@ func (s *testSuite4) TestWriteListPartitionTable2(c *C) { tk.MustQuery("select id,name from t order by id").Check(testkit.Rows("1 x", "2 b", "3 c", "4 d", "7 x")) // Test replace meet no partition error. _, err = tk.Exec("replace into t (id,name) values (10,'x'),(50,'x')") - c.Assert(err.Error(), Equals, "[table:1526]Table has no partition for value 50") + require.EqualError(t, err, "[table:1526]Table has no partition for value 50") tk.MustQuery("select id,name from t order by id").Check(testkit.Rows("1 x", "2 b", "3 c", "4 d", "7 x")) // --------------------------Test delete--------------------------- @@ -3426,8 +3301,11 @@ func (s *testSuite4) TestWriteListPartitionTable2(c *C) { tk.MustQuery("select id,name from t").Check(testkit.Rows()) } -func (s *testSuite4) TestWriteListColumnsPartitionTable1(c *C) { - tk := testkit.NewTestKitWithInit(c, s.store) +func TestWriteListColumnsPartitionTable1(t *testing.T) { + t.Parallel() + store, clean := testkit.CreateMockStore(t) + defer clean() + tk := testkit.NewTestKit(t, store) tk.MustExec("use test") tk.MustExec("set @@session.tidb_enable_list_partition = ON") @@ -3442,7 +3320,7 @@ func (s *testSuite4) TestWriteListColumnsPartitionTable1(c *C) { // Test add unique index failed. tk.MustExec("insert into t values (1, 'a'),(1,'b')") _, err := tk.Exec("alter table t add unique index idx (id)") - c.Assert(err.Error(), Equals, "[kv:1062]Duplicate entry '1' for key 'idx'") + require.EqualError(t, err, "[kv:1062]Duplicate entry '1' for key 'idx'") // Test add unique index success. tk.MustExec("delete from t where name='b'") tk.MustExec("alter table t add unique index idx (id)") @@ -3467,7 +3345,7 @@ func (s *testSuite4) TestWriteListColumnsPartitionTable1(c *C) { tk.MustQuery("select * from t partition(p3) order by id").Check(testkit.Rows()) // Test insert on duplicate error _, err = tk.Exec("insert into t values (3, 'a'), (11,'x') on duplicate key update id=id+1") - c.Assert(err.Error(), Equals, "[kv:1062]Duplicate entry '4' for key 'idx'") + require.EqualError(t, err, "[kv:1062]Duplicate entry '4' for key 'idx'") tk.MustQuery("select * from t order by id").Check(testkit.Rows("1 x", "3 x", "4 e", "5 g")) // Test insert ignore with duplicate tk.MustExec("insert ignore into t values (1, 'b'), (5,'a'),(null,'y')") @@ -3482,7 +3360,7 @@ func (s *testSuite4) TestWriteListColumnsPartitionTable1(c *C) { tk.MustQuery("select * from t partition(p3) order by id").Check(testkit.Rows(" y", "15 a")) // Test insert meet no partition error. _, err = tk.Exec("insert into t values (100, 'd')") - c.Assert(err.Error(), Equals, "[table:1526]Table has no partition for value from column_list") + require.EqualError(t, err, "[table:1526]Table has no partition for value from column_list") // --------------------------Test update--------------------------- // Test update 1 partition. @@ -3496,7 +3374,7 @@ func (s *testSuite4) TestWriteListColumnsPartitionTable1(c *C) { tk.MustQuery("select * from t order by id").Check(testkit.Rows("1 y", "2 y", "3 c")) // Test update meet duplicate error. _, err = tk.Exec("update t set id=2 where id = 1") - c.Assert(err.Error(), Equals, "[kv:1062]Duplicate entry '2' for key 'idx'") + require.EqualError(t, err, "[kv:1062]Duplicate entry '2' for key 'idx'") tk.MustQuery("select * from t order by id").Check(testkit.Rows("1 y", "2 y", "3 c")) // Test update multi-partitions @@ -3508,11 +3386,11 @@ func (s *testSuite4) TestWriteListColumnsPartitionTable1(c *C) { tk.MustQuery("select * from t order by id").Check(testkit.Rows("3 a", "10 a", "20 a")) // Test update meet duplicate error. _, err = tk.Exec("update t set id=id+17 where id in (3,10)") - c.Assert(err.Error(), Equals, "[kv:1062]Duplicate entry '20' for key 'idx'") + require.EqualError(t, err, "[kv:1062]Duplicate entry '20' for key 'idx'") tk.MustQuery("select * from t order by id").Check(testkit.Rows("3 a", "10 a", "20 a")) // Test update meet no partition error. _, err = tk.Exec("update t set id=id*2 where id in (3,20)") - c.Assert(err.Error(), Equals, "[table:1526]Table has no partition for value from column_list") + require.EqualError(t, err, "[table:1526]Table has no partition for value from column_list") tk.MustQuery("select * from t order by id").Check(testkit.Rows("3 a", "10 a", "20 a")) // --------------------------Test replace--------------------------- @@ -3531,7 +3409,7 @@ func (s *testSuite4) TestWriteListColumnsPartitionTable1(c *C) { tk.MustQuery("select * from t order by id").Check(testkit.Rows("1 x", "2 b", "3 c", "4 d", "7 x")) // Test replace meet no partition error. _, err = tk.Exec("replace into t values (10,'x'),(100,'x')") - c.Assert(err.Error(), Equals, "[table:1526]Table has no partition for value from column_list") + require.EqualError(t, err, "[table:1526]Table has no partition for value from column_list") tk.MustQuery("select * from t order by id").Check(testkit.Rows("1 x", "2 b", "3 c", "4 d", "7 x")) // --------------------------Test delete--------------------------- @@ -3552,8 +3430,11 @@ func (s *testSuite4) TestWriteListColumnsPartitionTable1(c *C) { } // TestWriteListColumnsPartitionTable2 test for write list partition when the partition by multi-columns. -func (s *testSuite4) TestWriteListColumnsPartitionTable2(c *C) { - tk := testkit.NewTestKitWithInit(c, s.store) +func TestWriteListColumnsPartitionTable2(t *testing.T) { + t.Parallel() + store, clean := testkit.CreateMockStore(t) + defer clean() + tk := testkit.NewTestKit(t, store) tk.MustExec("use test") tk.MustExec("set @@session.tidb_enable_list_partition = ON") tk.MustExec("drop table if exists t") @@ -3567,7 +3448,7 @@ func (s *testSuite4) TestWriteListColumnsPartitionTable2(c *C) { // Test add unique index failed. tk.MustExec("insert into t values ('w', 1, 1),('w', 1, 2)") _, err := tk.Exec("alter table t add unique index idx (location,id)") - c.Assert(err.Error(), Equals, "[kv:1062]Duplicate entry 'w-1' for key 'idx'") + require.EqualError(t, err, "[kv:1062]Duplicate entry 'w-1' for key 'idx'") // Test add unique index success. tk.MustExec("delete from t where a=2") tk.MustExec("alter table t add unique index idx (location,id)") @@ -3594,7 +3475,7 @@ func (s *testSuite4) TestWriteListColumnsPartitionTable2(c *C) { // Test insert on duplicate error tk.MustExec("insert into t values ('w', 2, 2), ('w', 1, 1)") _, err = tk.Exec("insert into t values ('w', 2, 3) on duplicate key update id=1") - c.Assert(err.Error(), Equals, "[kv:1062]Duplicate entry 'w-1' for key 'idx'") + require.EqualError(t, err, "[kv:1062]Duplicate entry 'w-1' for key 'idx'") tk.MustQuery("select * from t partition(p_west) order by id").Check(testkit.Rows("w 1 1", "w 2 2")) // Test insert ignore with duplicate tk.MustExec("insert ignore into t values ('w', 2, 2), ('w', 3, 3), ('n', 10, 10)") @@ -3607,13 +3488,13 @@ func (s *testSuite4) TestWriteListColumnsPartitionTable2(c *C) { tk.MustQuery("select * from t partition(p_south) order by id").Check(testkit.Rows("s 13 2", "s 14 14")) // Test insert meet no partition error. _, err = tk.Exec("insert into t values ('w', 5, 5)") - c.Assert(err.Error(), Equals, "[table:1526]Table has no partition for value from column_list") + require.EqualError(t, err, "[table:1526]Table has no partition for value from column_list") _, err = tk.Exec("insert into t values ('s', 5, 5)") - c.Assert(err.Error(), Equals, "[table:1526]Table has no partition for value from column_list") + require.EqualError(t, err, "[table:1526]Table has no partition for value from column_list") _, err = tk.Exec("insert into t values ('s', 100, 5)") - c.Assert(err.Error(), Equals, "[table:1526]Table has no partition for value from column_list") + require.EqualError(t, err, "[table:1526]Table has no partition for value from column_list") _, err = tk.Exec("insert into t values ('x', 1, 5)") - c.Assert(err.Error(), Equals, "[table:1526]Table has no partition for value from column_list") + require.EqualError(t, err, "[table:1526]Table has no partition for value from column_list") // --------------------------Test update--------------------------- // Test update 1 partition. @@ -3631,7 +3512,7 @@ func (s *testSuite4) TestWriteListColumnsPartitionTable2(c *C) { tk.MustQuery("select * from t partition(p_west) order by id,a").Check(testkit.Rows("w 1 5", "w 2 5", "w 3 6")) // Test update meet duplicate error. _, err = tk.Exec("update t set id=id+1 where location='w' and id<2") - c.Assert(err.Error(), Equals, "[kv:1062]Duplicate entry 'w-2' for key 'idx'") + require.EqualError(t, err, "[kv:1062]Duplicate entry 'w-2' for key 'idx'") tk.MustQuery("select * from t partition(p_west) order by id,a").Check(testkit.Rows("w 1 5", "w 2 5", "w 3 6")) // Test update multi-partitions @@ -3649,11 +3530,11 @@ func (s *testSuite4) TestWriteListColumnsPartitionTable2(c *C) { tk.MustQuery("select * from t order by id").Check(testkit.Rows("w 1 4", "w 2 4", "e 8 9", "n 11 15")) // Test update meet duplicate error. _, err = tk.Exec("update t set id=id+1 where location='w' and id in (1,2)") - c.Assert(err.Error(), Equals, "[kv:1062]Duplicate entry 'w-2' for key 'idx'") + require.EqualError(t, err, "[kv:1062]Duplicate entry 'w-2' for key 'idx'") tk.MustQuery("select * from t order by id").Check(testkit.Rows("w 1 4", "w 2 4", "e 8 9", "n 11 15")) // Test update meet no partition error. _, err = tk.Exec("update t set id=id+3 where location='w' and id in (1,2)") - c.Assert(err.Error(), Equals, "[table:1526]Table has no partition for value from column_list") + require.EqualError(t, err, "[table:1526]Table has no partition for value from column_list") tk.MustQuery("select * from t order by id").Check(testkit.Rows("w 1 4", "w 2 4", "e 8 9", "n 11 15")) // Test update that move from partition 1 to partition 2. // TODO: fix this @@ -3674,13 +3555,13 @@ func (s *testSuite4) TestWriteListColumnsPartitionTable2(c *C) { tk.MustQuery("select * from t order by id").Check(testkit.Rows("w 1 2", "e 5 5", "n 9 9", "n 10 10")) // Test replace meet no partition error. _, err = tk.Exec("replace into t values ('w', 5, 5)") - c.Assert(err.Error(), Equals, "[table:1526]Table has no partition for value from column_list") + require.EqualError(t, err, "[table:1526]Table has no partition for value from column_list") _, err = tk.Exec("replace into t values ('s', 5, 5)") - c.Assert(err.Error(), Equals, "[table:1526]Table has no partition for value from column_list") + require.EqualError(t, err, "[table:1526]Table has no partition for value from column_list") _, err = tk.Exec("replace into t values ('s', 100, 5)") - c.Assert(err.Error(), Equals, "[table:1526]Table has no partition for value from column_list") + require.EqualError(t, err, "[table:1526]Table has no partition for value from column_list") _, err = tk.Exec("replace into t values ('x', 1, 5)") - c.Assert(err.Error(), Equals, "[table:1526]Table has no partition for value from column_list") + require.EqualError(t, err, "[table:1526]Table has no partition for value from column_list") // --------------------------Test delete--------------------------- // Test delete 1 partition. @@ -3701,18 +3582,24 @@ func (s *testSuite4) TestWriteListColumnsPartitionTable2(c *C) { } // TestWriteListColumnsPartitionTable2 test for write list partition when the partition by multi-columns. -func (s *testSuite4) TestWriteListPartitionTableIssue21437(c *C) { - tk := testkit.NewTestKitWithInit(c, s.store) +func TestWriteListPartitionTableIssue21437(t *testing.T) { + t.Parallel() + store, clean := testkit.CreateMockStore(t) + defer clean() + tk := testkit.NewTestKit(t, store) tk.MustExec("use test") tk.MustExec("set @@session.tidb_enable_list_partition = ON") tk.MustExec("drop table if exists t") tk.MustExec(`create table t (a int) partition by list (a%10) (partition p0 values in (0,1));`) _, err := tk.Exec("replace into t values (null)") - c.Assert(err.Error(), Equals, "[table:1526]Table has no partition for value NULL") + require.EqualError(t, err, "[table:1526]Table has no partition for value NULL") } -func (s *testSuite4) TestListPartitionWithAutoRandom(c *C) { - tk := testkit.NewTestKitWithInit(c, s.store) +func TestListPartitionWithAutoRandom(t *testing.T) { + t.Parallel() + store, clean := testkit.CreateMockStore(t) + defer clean() + tk := testkit.NewTestKit(t, store) tk.MustExec("use test") tk.MustExec("set @@session.tidb_enable_list_partition = ON") tk.MustExec("drop table if exists t") @@ -3734,8 +3621,11 @@ func (s *testSuite4) TestListPartitionWithAutoRandom(c *C) { tk.MustQuery("select b from t where a=1").Check(testkit.Rows("4")) } -func (s *testSuite4) TestListPartitionWithAutoIncrement(c *C) { - tk := testkit.NewTestKitWithInit(c, s.store) +func TestListPartitionWithAutoIncrement(t *testing.T) { + t.Parallel() + store, clean := testkit.CreateMockStore(t) + defer clean() + tk := testkit.NewTestKit(t, store) tk.MustExec("use test") tk.MustExec("set @@session.tidb_enable_list_partition = ON") tk.MustExec("drop table if exists t") @@ -3757,8 +3647,11 @@ func (s *testSuite4) TestListPartitionWithAutoIncrement(c *C) { tk.MustQuery("select b from t where a=1").Check(testkit.Rows("4")) } -func (s *testSuite4) TestListPartitionWithGeneratedColumn(c *C) { - tk := testkit.NewTestKitWithInit(c, s.store) +func TestListPartitionWithGeneratedColumn(t *testing.T) { + t.Parallel() + store, clean := testkit.CreateMockStore(t) + defer clean() + tk := testkit.NewTestKit(t, store) tk.MustExec("use test") tk.MustExec("set @@session.tidb_enable_list_partition = ON") // Test for generated column with bigint type. @@ -3795,15 +3688,18 @@ func (s *testSuite4) TestListPartitionWithGeneratedColumn(c *C) { // Test for insert meet no partition error _, err := tk.Exec("insert into t (a) values (11)") - c.Assert(table.ErrNoPartitionForGivenValue.Equal(err), IsTrue) + require.True(t, table.ErrNoPartitionForGivenValue.Equal(err)) // Test for update meet no partition error _, err = tk.Exec("update t set a=a+10 where a = 2") - c.Assert(table.ErrNoPartitionForGivenValue.Equal(err), IsTrue) + require.True(t, table.ErrNoPartitionForGivenValue.Equal(err)) } } -func (s *testSuite4) TestListPartitionWithGeneratedColumn1(c *C) { - tk := testkit.NewTestKitWithInit(c, s.store) +func TestListPartitionWithGeneratedColumn1(t *testing.T) { + t.Parallel() + store, clean := testkit.CreateMockStore(t) + defer clean() + tk := testkit.NewTestKit(t, store) tk.MustExec("use test") tk.MustExec("set @@session.tidb_enable_list_partition = ON") // Test for generated column with year type. @@ -3836,11 +3732,10 @@ func (s *testSuite4) TestListPartitionWithGeneratedColumn1(c *C) { // Test for insert meet no partition error _, err := tk.Exec("insert into t (a) values (11)") - c.Assert(err.Error(), Equals, "[table:1526]Table has no partition for value 2011") + require.EqualError(t, err, "[table:1526]Table has no partition for value 2011") // Test for update meet no partition error _, err = tk.Exec("update t set a=a+10 where a = 2") - c.Assert(err.Error(), Equals, "[table:1526]Table has no partition for value 2012") - + require.EqualError(t, err, "[table:1526]Table has no partition for value 2012") tk.MustExec("delete from t") // Test for insert @@ -3863,15 +3758,18 @@ func (s *testSuite4) TestListPartitionWithGeneratedColumn1(c *C) { // Test for insert meet no partition error _, err = tk.Exec("insert into t (a) values (2011)") - c.Assert(err.Error(), Equals, "[table:1526]Table has no partition for value 2011") + require.EqualError(t, err, "[table:1526]Table has no partition for value 2011") // Test for update meet no partition error _, err = tk.Exec("update t set a=a+10 where a = 2002") - c.Assert(err.Error(), Equals, "[table:1526]Table has no partition for value 2012") + require.EqualError(t, err, "[table:1526]Table has no partition for value 2012") } } -func (s *testSuite4) TestListPartitionWithGeneratedColumn2(c *C) { - tk := testkit.NewTestKitWithInit(c, s.store) +func TestListPartitionWithGeneratedColumn2(t *testing.T) { + t.Parallel() + store, clean := testkit.CreateMockStore(t) + defer clean() + tk := testkit.NewTestKit(t, store) tk.MustExec("use test") tk.MustExec("set @@session.tidb_enable_list_partition = ON") tableDefs := []string{ @@ -3912,8 +3810,11 @@ func (s *testSuite4) TestListPartitionWithGeneratedColumn2(c *C) { } } -func (s *testSuite4) TestListColumnsPartitionWithGeneratedColumn(c *C) { - tk := testkit.NewTestKitWithInit(c, s.store) +func TestListColumnsPartitionWithGeneratedColumn(t *testing.T) { + t.Parallel() + store, clean := testkit.CreateMockStore(t) + defer clean() + tk := testkit.NewTestKit(t, store) tk.MustExec("use test") tk.MustExec("set @@session.tidb_enable_list_partition = ON") // Test for generated column with substr expression. @@ -3936,111 +3837,23 @@ func (s *testSuite4) TestListColumnsPartitionWithGeneratedColumn(c *C) { } } -func (s *testSerialSuite2) TestListColumnsPartitionWithGlobalIndex(c *C) { - tk := testkit.NewTestKitWithInit(c, s.store) - tk.MustExec("use test") - tk.MustExec("set @@session.tidb_enable_list_partition = ON") - // Test generated column with global index - restoreConfig := config.RestoreFunc() - defer restoreConfig() - config.UpdateGlobal(func(conf *config.Config) { - conf.EnableGlobalIndex = true - }) - tableDefs := []string{ - // Test for virtual generated column with global index - `create table t (a varchar(10), b varchar(1) GENERATED ALWAYS AS (substr(a,1,1)) VIRTUAL) partition by list columns(b) (partition p0 values in ('a','c'), partition p1 values in ('b','d'));`, - // Test for stored generated column with global index - `create table t (a varchar(10), b varchar(1) GENERATED ALWAYS AS (substr(a,1,1)) STORED) partition by list columns(b) (partition p0 values in ('a','c'), partition p1 values in ('b','d'));`, - } - for _, tbl := range tableDefs { - tk.MustExec("drop table if exists t") - tk.MustExec(tbl) - tk.MustExec("alter table t add unique index (a)") - tk.MustExec("insert into t (a) values ('aaa'),('abc'),('acd')") - tk.MustQuery("select a from t partition (p0) order by a").Check(testkit.Rows("aaa", "abc", "acd")) - tk.MustQuery("select * from t where a = 'abc' order by a").Check(testkit.Rows("abc a")) - tk.MustExec("update t set a='bbb' where a = 'aaa'") - tk.MustExec("admin check table t") - tk.MustQuery("select a from t order by a").Check(testkit.Rows("abc", "acd", "bbb")) - // TODO: fix below test. - //tk.MustQuery("select a from t partition (p0) order by a").Check(testkit.Rows("abc", "acd")) - //tk.MustQuery("select a from t partition (p1) order by a").Check(testkit.Rows("bbb")) - tk.MustQuery("select * from t where a = 'bbb' order by a").Check(testkit.Rows("bbb b")) - // Test insert meet duplicate error. - _, err := tk.Exec("insert into t (a) values ('abc')") - c.Assert(err, NotNil) - // Test insert on duplicate update - tk.MustExec("insert into t (a) values ('abc') on duplicate key update a='bbc'") - tk.MustQuery("select a from t order by a").Check(testkit.Rows("acd", "bbb", "bbc")) - tk.MustQuery("select * from t where a = 'bbc'").Check(testkit.Rows("bbc b")) - // TODO: fix below test. - //tk.MustQuery("select a from t partition (p0) order by a").Check(testkit.Rows("acd")) - //tk.MustQuery("select a from t partition (p1) order by a").Check(testkit.Rows("bbb", "bbc")) - } -} - -func (s *testSerialSuite) TestIssue20724(c *C) { - collate.SetNewCollationEnabledForTest(true) - defer collate.SetNewCollationEnabledForTest(false) - - tk := testkit.NewTestKitWithInit(c, s.store) - tk.MustExec("use test") - tk.MustExec("drop table if exists t1") - tk.MustExec("create table t1(a varchar(10) collate utf8mb4_general_ci)") - tk.MustExec("insert into t1 values ('a')") - tk.MustExec("update t1 set a = 'A'") - tk.MustQuery("select * from t1").Check(testkit.Rows("A")) - tk.MustExec("drop table t1") -} - -func (s *testSerialSuite) TestIssue20840(c *C) { - collate.SetNewCollationEnabledForTest(true) - defer collate.SetNewCollationEnabledForTest(false) - - tk := testkit.NewTestKitWithInit(c, s.store) - tk.MustExec("use test") - tk.MustExec("drop table if exists t1") - tk.Se.GetSessionVars().EnableClusteredIndex = variable.ClusteredIndexDefModeIntOnly - tk.MustExec("create table t1 (i varchar(20) unique key) collate=utf8mb4_general_ci") - tk.MustExec("insert into t1 values ('a')") - tk.MustExec("replace into t1 values ('A')") - tk.MustQuery("select * from t1").Check(testkit.Rows("A")) - tk.MustExec("drop table t1") -} - -func (s *testSerialSuite) TestIssueInsertPrefixIndexForNonUTF8Collation(c *C) { - collate.SetNewCollationEnabledForTest(true) - defer collate.SetNewCollationEnabledForTest(false) - - tk := testkit.NewTestKitWithInit(c, s.store) - tk.MustExec("use test") - tk.MustExec("drop table if exists t1, t2, t3") - tk.MustExec("create table t1 ( c_int int, c_str varchar(40) character set ascii collate ascii_bin, primary key(c_int, c_str(8)) clustered , unique key(c_str))") - tk.MustExec("create table t2 ( c_int int, c_str varchar(40) character set latin1 collate latin1_bin, primary key(c_int, c_str(8)) clustered , unique key(c_str))") - tk.MustExec("insert into t1 values (3, 'fervent brattain')") - tk.MustExec("insert into t2 values (3, 'fervent brattain')") - tk.MustExec("admin check table t1") - tk.MustExec("admin check table t2") - - tk.MustExec("create table t3 (x varchar(40) CHARACTER SET ascii COLLATE ascii_bin, UNIQUE KEY uk(x(4)))") - tk.MustExec("insert into t3 select 'abc '") - tk.MustGetErrCode("insert into t3 select 'abc d'", 1062) -} - -func (s *testSerialSuite) TestIssue22496(c *C) { - tk := testkit.NewTestKit(c, s.store) +func TestIssue22496(t *testing.T) { + t.Parallel() + store, clean := testkit.CreateMockStore(t) + defer clean() + tk := testkit.NewTestKit(t, store) tk.MustExec("use test") tk.MustExec("drop table if exists t12") tk.MustExec("create table t12(d decimal(15,2));") _, err := tk.Exec("insert into t12 values('1,9999.00')") - c.Assert(err, NotNil) + require.Error(t, err) tk.MustExec("set sql_mode=''") tk.MustExec("insert into t12 values('1,999.00');") tk.MustQuery("SELECT * FROM t12;").Check(testkit.Rows("1.00")) tk.MustExec("drop table t12") } -func (s *testSuite) TestEqualDatumsAsBinary(c *C) { +func TestEqualDatumsAsBinary(t *testing.T) { tests := []struct { a []interface{} b []interface{} @@ -4064,12 +3877,15 @@ func (s *testSuite) TestEqualDatumsAsBinary(c *C) { {[]interface{}{nil}, []interface{}{1}, false}, } for _, tt := range tests { - testEqualDatumsAsBinary(c, tt.a, tt.b, tt.same) + testEqualDatumsAsBinary(t, tt.a, tt.b, tt.same) } } -func (s *testSuite) TestIssue21232(c *C) { - tk := testkit.NewTestKit(c, s.store) +func TestIssue21232(t *testing.T) { + t.Parallel() + store, clean := testkit.CreateMockStore(t) + defer clean() + tk := testkit.NewTestKit(t, store) tk.MustExec("use test") tk.MustExec("drop table if exists t, t1") tk.MustExec("create table t(a varchar(1), index idx(a))") @@ -4087,11 +3903,11 @@ func (s *testSuite) TestIssue21232(c *C) { tk.MustQuery("select * from t").Check(testkit.Rows("a", "b")) } -func testEqualDatumsAsBinary(c *C, a []interface{}, b []interface{}, same bool) { +func testEqualDatumsAsBinary(t *testing.T, a []interface{}, b []interface{}, same bool) { sc := new(stmtctx.StatementContext) re := new(executor.ReplaceExec) sc.IgnoreTruncate = true res, err := re.EqualDatumsAsBinary(sc, types.MakeDatums(a...), types.MakeDatums(b...)) - c.Assert(err, IsNil) - c.Assert(res, Equals, same, Commentf("a: %v, b: %v", a, b)) + require.NoError(t, err) + require.Equal(t, same, res, "a: %v, b: %v", a, b) } diff --git a/planner/core/common_plans.go b/planner/core/common_plans.go index 7b346f6183083..10241797b6fe9 100644 --- a/planner/core/common_plans.go +++ b/planner/core/common_plans.go @@ -1310,6 +1310,8 @@ func (e *Explain) explainPlanInRowFormat(p Plan, taskType, driverSide, indent st } case *PhysicalCTE: e.ctes = append(e.ctes, x) + case *PhysicalShuffleReceiverStub: + err = e.explainPlanInRowFormat(x.DataSource, "root", "", childIndent, true) } return } diff --git a/planner/core/physical_plans.go b/planner/core/physical_plans.go index b7a5698bc2509..f9cdca27dc42f 100644 --- a/planner/core/physical_plans.go +++ b/planner/core/physical_plans.go @@ -1325,8 +1325,10 @@ const ( type PhysicalShuffleReceiverStub struct { physicalSchemaProducer - // Worker points to `executor.shuffleReceiver`. + // Receiver points to `executor.shuffleReceiver`. Receiver unsafe.Pointer + // DataSource is the PhysicalPlan of the Receiver. + DataSource PhysicalPlan } // CollectPlanStatsVersion uses to collect the statistics version of the plan. diff --git a/server/conn.go b/server/conn.go index 8658b8fe61bc8..0277bd40a49be 100644 --- a/server/conn.go +++ b/server/conn.go @@ -707,7 +707,7 @@ func (cc *clientConn) readOptionalSSLRequestAndHandshakeResponse(ctx context.Con func (cc *clientConn) handleAuthPlugin(ctx context.Context, resp *handshakeResponse41) error { if resp.Capability&mysql.ClientPluginAuth > 0 { - newAuth, err := cc.checkAuthPlugin(ctx, &resp.AuthPlugin) + newAuth, err := cc.checkAuthPlugin(ctx, resp) if err != nil { logutil.Logger(ctx).Warn("failed to check the user authplugin", zap.Error(err)) } @@ -830,7 +830,7 @@ func (cc *clientConn) openSessionAndDoAuth(authData []byte, authPlugin string) e } // Check if the Authentication Plugin of the server, client and user configuration matches -func (cc *clientConn) checkAuthPlugin(ctx context.Context, authPlugin *string) ([]byte, error) { +func (cc *clientConn) checkAuthPlugin(ctx context.Context, resp *handshakeResponse41) ([]byte, error) { // Open a context unless this was done before. if cc.ctx == nil { err := cc.openSession() @@ -839,12 +839,21 @@ func (cc *clientConn) checkAuthPlugin(ctx context.Context, authPlugin *string) ( } } - userplugin, err := cc.ctx.AuthPluginForUser(&auth.UserIdentity{Username: cc.user, Hostname: cc.peerHost}) + authData := resp.Auth + hasPassword := "YES" + if len(authData) == 0 { + hasPassword = "NO" + } + host, _, err := cc.PeerHost(hasPassword) + if err != nil { + return nil, err + } + userplugin, err := cc.ctx.AuthPluginForUser(&auth.UserIdentity{Username: cc.user, Hostname: host}) if err != nil { return nil, err } if userplugin == mysql.AuthSocket { - *authPlugin = mysql.AuthSocket + resp.AuthPlugin = mysql.AuthSocket user, err := user.LookupId(fmt.Sprint(cc.socketCredUID)) if err != nil { return nil, err @@ -854,7 +863,7 @@ func (cc *clientConn) checkAuthPlugin(ctx context.Context, authPlugin *string) ( if len(userplugin) == 0 { logutil.Logger(ctx).Warn("No user plugin set, assuming MySQL Native Password", zap.String("user", cc.user), zap.String("host", cc.peerHost)) - *authPlugin = mysql.AuthNativePassword + resp.AuthPlugin = mysql.AuthNativePassword return nil, nil } @@ -863,12 +872,12 @@ func (cc *clientConn) checkAuthPlugin(ctx context.Context, authPlugin *string) ( // or if the authentication method send by the server doesn't match the authentication // method send by the client (*authPlugin) then we need to switch the authentication // method to match the one configured for that specific user. - if (cc.authPlugin != userplugin) || (cc.authPlugin != *authPlugin) { + if (cc.authPlugin != userplugin) || (cc.authPlugin != resp.AuthPlugin) { authData, err := cc.authSwitchRequest(ctx, userplugin) if err != nil { return nil, err } - *authPlugin = userplugin + resp.AuthPlugin = userplugin return authData, nil } diff --git a/server/conn_test.go b/server/conn_test.go index 06b4b3a38c926..34ec75124a828 100644 --- a/server/conn_test.go +++ b/server/conn_test.go @@ -943,3 +943,47 @@ func TestHandleAuthPlugin(t *testing.T) { err = cc.handleAuthPlugin(ctx, &resp) require.NoError(t, err) } + +func TestAuthPlugin2(t *testing.T) { + + t.Parallel() + + store, clean := testkit.CreateMockStore(t) + defer clean() + + cfg := newTestConfig() + cfg.Socket = "" + cfg.Port = 0 + cfg.Status.StatusPort = 0 + + drv := NewTiDBDriver(store) + srv, err := NewServer(cfg, drv) + require.NoError(t, err) + + cc := &clientConn{ + connectionID: 1, + alloc: arena.NewAllocator(1024), + chunkAlloc: chunk.NewAllocator(), + pkt: &packetIO{ + bufWriter: bufio.NewWriter(bytes.NewBuffer(nil)), + }, + server: srv, + user: "root", + } + ctx := context.Background() + se, _ := session.CreateSession4Test(store) + tc := &TiDBContext{ + Session: se, + stmts: make(map[int]*TiDBStatement), + } + cc.ctx = tc + + resp := handshakeResponse41{ + Capability: mysql.ClientProtocol41 | mysql.ClientPluginAuth, + } + + cc.isUnixSocket = true + _, err = cc.checkAuthPlugin(ctx, &resp) + require.NoError(t, err) + +} diff --git a/statistics/builder.go b/statistics/builder.go index 13edd2457fd75..cff117547f619 100644 --- a/statistics/builder.go +++ b/statistics/builder.go @@ -23,6 +23,7 @@ import ( "github.com/pingcap/tidb/sessionctx/stmtctx" "github.com/pingcap/tidb/types" "github.com/pingcap/tidb/util/codec" + "github.com/pingcap/tidb/util/collate" ) // SortedBuilder is used to build histograms for PK and index. @@ -67,7 +68,7 @@ func (b *SortedBuilder) Iterate(data types.Datum) error { b.hist.NDV = 1 return nil } - cmp, err := b.hist.GetUpper(int(b.bucketIdx)).CompareDatum(b.sc, &data) + cmp, err := b.hist.GetUpper(int(b.bucketIdx)).Compare(b.sc, &data, collate.GetBinaryCollator()) if err != nil { return errors.Trace(err) } @@ -158,7 +159,7 @@ func buildHist(sc *stmtctx.StatementContext, hg *Histogram, samples []*SampleIte hg.AppendBucket(&samples[0].Value, &samples[0].Value, int64(sampleFactor), int64(ndvFactor)) for i := int64(1); i < sampleNum; i++ { corrXYSum += float64(i) * float64(samples[i].Ordinal) - cmp, err := hg.GetUpper(bucketIdx).CompareDatum(sc, &samples[i].Value) + cmp, err := hg.GetUpper(bucketIdx).Compare(sc, &samples[i].Value, collate.GetBinaryCollator()) if err != nil { return 0, errors.Trace(err) } diff --git a/store/mockstore/mockcopr/aggregate.go b/store/mockstore/mockcopr/aggregate.go index 0a0dd6d6cfb56..1e7bcc1a9207a 100644 --- a/store/mockstore/mockcopr/aggregate.go +++ b/store/mockstore/mockcopr/aggregate.go @@ -24,6 +24,7 @@ import ( "github.com/pingcap/tidb/types" "github.com/pingcap/tidb/util/chunk" "github.com/pingcap/tidb/util/codec" + "github.com/pingcap/tidb/util/collate" ) type aggCtxsMapper map[string][]*aggregation.AggEvaluateContext @@ -208,6 +209,7 @@ type streamAggExec struct { aggExprs []aggregation.Aggregation aggCtxs []*aggregation.AggEvaluateContext groupByExprs []expression.Expression + groupByCollators []collate.Collator relatedColOffsets []int row []types.Datum tmpGroupByRow []types.Datum @@ -288,7 +290,7 @@ func (e *streamAggExec) meetNewGroup(row [][]byte) (bool, error) { return false, errors.Trace(err) } if matched { - c, err := d.CompareDatum(e.evalCtx.sc, &e.nextGroupByRow[i]) + c, err := d.Compare(e.evalCtx.sc, &e.nextGroupByRow[i], e.groupByCollators[i]) if err != nil { return false, errors.Trace(err) } diff --git a/store/mockstore/mockcopr/cop_handler_dag.go b/store/mockstore/mockcopr/cop_handler_dag.go index 4d71a1caa3994..2fd9d8f73d4b3 100644 --- a/store/mockstore/mockcopr/cop_handler_dag.go +++ b/store/mockstore/mockcopr/cop_handler_dag.go @@ -396,12 +396,17 @@ func (h coprHandler) buildStreamAgg(ctx *dagContext, executor *tipb.Executor) (* for _, agg := range aggs { aggCtxs = append(aggCtxs, agg.CreateContext(ctx.evalCtx.sc)) } + groupByCollators := make([]collate.Collator, 0, len(groupBys)) + for _, expr := range groupBys { + groupByCollators = append(groupByCollators, collate.GetCollator(expr.GetType().Collate)) + } return &streamAggExec{ evalCtx: ctx.evalCtx, aggExprs: aggs, aggCtxs: aggCtxs, groupByExprs: groupBys, + groupByCollators: groupByCollators, currGroupByValues: make([][]byte, 0), relatedColOffsets: relatedColOffsets, row: make([]types.Datum, len(ctx.evalCtx.columnInfos)), diff --git a/testkit/testkit.go b/testkit/testkit.go index a94cd076e86fc..50af5e0178a1b 100644 --- a/testkit/testkit.go +++ b/testkit/testkit.go @@ -228,6 +228,12 @@ func (tk *TestKit) MustUseIndex(sql string, index string, args ...interface{}) b return false } +// CheckExecResult checks the affected rows and the insert id after executing MustExec. +func (tk *TestKit) CheckExecResult(affectedRows, insertID int64) { + tk.require.Equal(int64(tk.Session().AffectedRows()), affectedRows) + tk.require.Equal(int64(tk.Session().LastInsertID()), insertID) +} + // WithPruneMode run test case under prune mode. func WithPruneMode(tk *TestKit, mode variable.PartitionPruneMode, f func()) { tk.MustExec("set @@tidb_partition_prune_mode=`" + string(mode) + "`") diff --git a/util/collate/collate.go b/util/collate/collate.go index 4f73b89b6742d..3cba9d6f572e5 100644 --- a/util/collate/collate.go +++ b/util/collate/collate.go @@ -154,6 +154,11 @@ func GetCollator(collate string) Collator { return binCollatorInstance } +// GetBinaryCollator gets the binary collator, it is often used when we want to apply binary compare. +func GetBinaryCollator() Collator { + return binCollatorInstance +} + // GetCollatorByID get the collator according to id, it will return the binary collator if the corresponding collator doesn't exist. func GetCollatorByID(id int) Collator { if atomic.LoadInt32(&newCollationEnabled) == 1 {