github.com/whtcorpsinc/milevadb-prod@v0.0.0-20211104133533-f57f4be3b597/interlock/interlocking_directorate_test.go (about)

     1  // Copyright 2020 WHTCORPS INC, Inc.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // See the License for the specific language governing permissions and
    12  // limitations under the License.
    13  
    14  package interlock_test
    15  
    16  import (
    17  	"context"
    18  	"flag"
    19  	"fmt"
    20  	"io/ioutil"
    21  	"math"
    22  	"net"
    23  	"os"
    24  	"strconv"
    25  	"strings"
    26  	"sync"
    27  	"sync/atomic"
    28  	"testing"
    29  	"time"
    30  
    31  	"github.com/golang/protobuf/proto"
    32  	"github.com/whtcorpsinc/BerolinaSQL"
    33  	"github.com/whtcorpsinc/BerolinaSQL/allegrosql"
    34  	"github.com/whtcorpsinc/BerolinaSQL/perceptron"
    35  	"github.com/whtcorpsinc/BerolinaSQL/terror"
    36  	. "github.com/whtcorpsinc/check"
    37  	pb "github.com/whtcorpsinc/ekvproto/pkg/ekvrpcpb"
    38  	"github.com/whtcorpsinc/errors"
    39  	"github.com/whtcorpsinc/failpoint"
    40  	"github.com/whtcorpsinc/fidelpb/go-fidelpb"
    41  	"github.com/whtcorpsinc/milevadb/blockcodec"
    42  	"github.com/whtcorpsinc/milevadb/causet"
    43  	"github.com/whtcorpsinc/milevadb/causet/blocks"
    44  	causetembedded "github.com/whtcorpsinc/milevadb/causet/embedded"
    45  	"github.com/whtcorpsinc/milevadb/causetstore/einsteindb"
    46  	"github.com/whtcorpsinc/milevadb/causetstore/einsteindb/einsteindbrpc"
    47  	"github.com/whtcorpsinc/milevadb/causetstore/einsteindb/oracle"
    48  	"github.com/whtcorpsinc/milevadb/causetstore/mockstore"
    49  	"github.com/whtcorpsinc/milevadb/causetstore/mockstore/cluster"
    50  	"github.com/whtcorpsinc/milevadb/config"
    51  	"github.com/whtcorpsinc/milevadb/dbs"
    52  	"github.com/whtcorpsinc/milevadb/ekv"
    53  	"github.com/whtcorpsinc/milevadb/interlock"
    54  	"github.com/whtcorpsinc/milevadb/memex"
    55  	"github.com/whtcorpsinc/milevadb/petri"
    56  	"github.com/whtcorpsinc/milevadb/petri/infosync"
    57  	"github.com/whtcorpsinc/milevadb/schemareplicant"
    58  	"github.com/whtcorpsinc/milevadb/server"
    59  	"github.com/whtcorpsinc/milevadb/soliton"
    60  	"github.com/whtcorpsinc/milevadb/soliton/admin"
    61  	"github.com/whtcorpsinc/milevadb/soliton/gcutil"
    62  	"github.com/whtcorpsinc/milevadb/soliton/logutil"
    63  	"github.com/whtcorpsinc/milevadb/soliton/mock"
    64  	"github.com/whtcorpsinc/milevadb/soliton/rowcodec"
    65  	"github.com/whtcorpsinc/milevadb/soliton/solitonutil"
    66  	"github.com/whtcorpsinc/milevadb/soliton/testkit"
    67  	"github.com/whtcorpsinc/milevadb/soliton/testleak"
    68  	"github.com/whtcorpsinc/milevadb/soliton/timeutil"
    69  	"github.com/whtcorpsinc/milevadb/spacetime"
    70  	"github.com/whtcorpsinc/milevadb/spacetime/autoid"
    71  	"github.com/whtcorpsinc/milevadb/statistics"
    72  	"github.com/whtcorpsinc/milevadb/stochastik"
    73  	"github.com/whtcorpsinc/milevadb/stochastikctx"
    74  	"github.com/whtcorpsinc/milevadb/stochastikctx/stmtctx"
    75  	"github.com/whtcorpsinc/milevadb/stochastikctx/variable"
    76  	"github.com/whtcorpsinc/milevadb/types"
    77  	"google.golang.org/grpc"
    78  )
    79  
    80  func TestT(t *testing.T) {
    81  	CustomVerboseFlag = true
    82  	*CustomParallelSuiteFlag = true
    83  	logLevel := os.Getenv("log_level")
    84  	logutil.InitLogger(logutil.NewLogConfig(logLevel, logutil.DefaultLogFormat, "", logutil.EmptyFileLogConfig, false))
    85  	autoid.SetStep(5000)
    86  
    87  	config.UFIDelateGlobal(func(conf *config.Config) {
    88  		conf.Log.SlowThreshold = 30000 // 30s
    89  	})
    90  	tmFIDelir := config.GetGlobalConfig().TempStoragePath
    91  	_ = os.RemoveAll(tmFIDelir) // clean the uncleared temp file during the last run.
    92  	_ = os.MkdirAll(tmFIDelir, 0755)
    93  	testleak.BeforeTest()
    94  	TestingT(t)
    95  	testleak.AfterTestT(t)()
    96  }
    97  
    98  var _ = Suite(&testSuite{&baseTestSuite{}})
    99  var _ = Suite(&testSuiteP1{&baseTestSuite{}})
   100  var _ = Suite(&testSuiteP2{&baseTestSuite{}})
   101  var _ = Suite(&testSuite1{})
   102  var _ = Suite(&testSuite2{&baseTestSuite{}})
   103  var _ = Suite(&testSuite3{&baseTestSuite{}})
   104  var _ = Suite(&testSuite4{&baseTestSuite{}})
   105  var _ = Suite(&testSuite5{&baseTestSuite{}})
   106  var _ = Suite(&testSuiteJoin1{&baseTestSuite{}})
   107  var _ = Suite(&testSuiteJoin2{&baseTestSuite{}})
   108  var _ = Suite(&testSuiteJoin3{&baseTestSuite{}})
   109  var _ = SerialSuites(&testSuiteJoinSerial{&baseTestSuite{}})
   110  var _ = Suite(&testSuiteAgg{baseTestSuite: &baseTestSuite{}})
   111  var _ = Suite(&testSuite6{&baseTestSuite{}})
   112  var _ = Suite(&testSuite7{&baseTestSuite{}})
   113  var _ = Suite(&testSuite8{&baseTestSuite{}})
   114  var _ = Suite(&testClusteredSuite{&baseTestSuite{}})
   115  var _ = SerialSuites(&testShowStatsSuite{&baseTestSuite{}})
   116  var _ = Suite(&testBypassSuite{})
   117  var _ = Suite(&testUFIDelateSuite{})
   118  var _ = Suite(&testPointGetSuite{})
   119  var _ = Suite(&testBatchPointGetSuite{})
   120  var _ = SerialSuites(&testRecoverBlock{})
   121  var _ = SerialSuites(&testMemBlockReaderSuite{&testClusterBlockBase{}})
   122  var _ = SerialSuites(&testFlushSuite{})
   123  var _ = SerialSuites(&testAutoRandomSuite{&baseTestSuite{}})
   124  var _ = SerialSuites(&testClusterBlockSuite{})
   125  var _ = SerialSuites(&testPrepareSerialSuite{&baseTestSuite{}})
   126  var _ = SerialSuites(&testSplitBlock{&baseTestSuite{}})
   127  var _ = Suite(&testSuiteWithData{baseTestSuite: &baseTestSuite{}})
   128  var _ = SerialSuites(&testSerialSuite1{&baseTestSuite{}})
   129  var _ = SerialSuites(&testSlowQuery{&baseTestSuite{}})
   130  var _ = Suite(&partitionBlockSuite{&baseTestSuite{}})
   131  var _ = SerialSuites(&tiflashTestSuite{})
   132  var _ = SerialSuites(&testSerialSuite{&baseTestSuite{}})
   133  
   134  type testSuite struct{ *baseTestSuite }
   135  type testSuiteP1 struct{ *baseTestSuite }
   136  type testSuiteP2 struct{ *baseTestSuite }
   137  type testSplitBlock struct{ *baseTestSuite }
   138  type testSuiteWithData struct {
   139  	*baseTestSuite
   140  	testData solitonutil.TestData
   141  }
   142  type testSlowQuery struct{ *baseTestSuite }
   143  type partitionBlockSuite struct{ *baseTestSuite }
   144  type testSerialSuite struct{ *baseTestSuite }
   145  
   146  type baseTestSuite struct {
   147  	cluster     cluster.Cluster
   148  	causetstore ekv.CausetStorage
   149  	petri       *petri.Petri
   150  	*BerolinaSQL.BerolinaSQL
   151  	ctx *mock.Context
   152  }
   153  
   154  var mockEinsteinDB = flag.Bool("mockEinsteinDB", true, "use mock einsteindb causetstore in interlock test")
   155  
   156  func (s *baseTestSuite) SetUpSuite(c *C) {
   157  	s.BerolinaSQL = BerolinaSQL.New()
   158  	flag.Lookup("mockEinsteinDB")
   159  	useMockEinsteinDB := *mockEinsteinDB
   160  	if useMockEinsteinDB {
   161  		causetstore, err := mockstore.NewMockStore(
   162  			mockstore.WithClusterInspector(func(c cluster.Cluster) {
   163  				mockstore.BootstrapWithSingleStore(c)
   164  				s.cluster = c
   165  			}),
   166  		)
   167  		c.Assert(err, IsNil)
   168  		s.causetstore = causetstore
   169  		stochastik.SetSchemaLease(0)
   170  		stochastik.DisableStats4Test()
   171  	}
   172  	d, err := stochastik.BootstrapStochastik(s.causetstore)
   173  	c.Assert(err, IsNil)
   174  	d.SetStatsUFIDelating(true)
   175  	s.petri = d
   176  	config.UFIDelateGlobal(func(conf *config.Config) {
   177  		conf.OOMCausetAction = config.OOMCausetActionLog
   178  	})
   179  }
   180  
   181  func (s *testSuiteWithData) SetUpSuite(c *C) {
   182  	s.baseTestSuite.SetUpSuite(c)
   183  	var err error
   184  	s.testData, err = solitonutil.LoadTestSuiteData("testdata", "interlock_suite")
   185  	c.Assert(err, IsNil)
   186  }
   187  
   188  func (s *testSuiteWithData) TearDownSuite(c *C) {
   189  	s.baseTestSuite.TearDownSuite(c)
   190  	c.Assert(s.testData.GenerateOutputIfNeeded(), IsNil)
   191  }
   192  
   193  func (s *baseTestSuite) TearDownSuite(c *C) {
   194  	s.petri.Close()
   195  	s.causetstore.Close()
   196  }
   197  
   198  func (s *testSuiteP1) TestPessimisticSelectForUFIDelate(c *C) {
   199  	tk := testkit.NewTestKit(c, s.causetstore)
   200  	tk.MustInterDirc("use test")
   201  	tk.MustInterDirc("drop causet if exists t")
   202  	tk.MustInterDirc("create causet t(id int primary key, a int)")
   203  	tk.MustInterDirc("insert into t values(1, 1)")
   204  	tk.MustInterDirc("begin PESSIMISTIC")
   205  	tk.MustQuery("select a from t where id=1 for uFIDelate").Check(testkit.Events("1"))
   206  	tk.MustInterDirc("uFIDelate t set a=a+1 where id=1")
   207  	tk.MustInterDirc("commit")
   208  	tk.MustQuery("select a from t where id=1").Check(testkit.Events("2"))
   209  }
   210  
   211  func (s *testSuite) TearDownTest(c *C) {
   212  	tk := testkit.NewTestKit(c, s.causetstore)
   213  	tk.MustInterDirc("use test")
   214  	r := tk.MustQuery("show blocks")
   215  	for _, tb := range r.Events() {
   216  		blockName := tb[0]
   217  		tk.MustInterDirc(fmt.Sprintf("drop causet %v", blockName))
   218  	}
   219  }
   220  
   221  func (s *testSuiteP1) TestBind(c *C) {
   222  	tk := testkit.NewTestKit(c, s.causetstore)
   223  	tk.MustInterDirc("use test")
   224  	tk.MustInterDirc("drop causet if exists testbind")
   225  
   226  	tk.MustInterDirc("create causet testbind(i int, s varchar(20))")
   227  	tk.MustInterDirc("create index index_t on testbind(i,s)")
   228  	tk.MustInterDirc("create global binding for select * from testbind using select * from testbind use index for join(index_t)")
   229  	c.Assert(len(tk.MustQuery("show global bindings").Events()), Equals, 1)
   230  
   231  	tk.MustInterDirc("create stochastik binding for select * from testbind using select * from testbind use index for join(index_t)")
   232  	c.Assert(len(tk.MustQuery("show stochastik bindings").Events()), Equals, 1)
   233  	tk.MustInterDirc("drop stochastik binding for select * from testbind")
   234  }
   235  
   236  func (s *testSuiteP1) TestChange(c *C) {
   237  	tk := testkit.NewTestKit(c, s.causetstore)
   238  	tk.MustInterDirc("use test")
   239  	tk.MustInterDirc("drop causet if exists t")
   240  	tk.MustInterDirc("create causet t(a int)")
   241  	tk.MustInterDirc("alter causet t change a b int")
   242  	tk.MustInterDirc("alter causet t change b c bigint")
   243  	c.Assert(tk.InterDircToErr("alter causet t change c d varchar(100)"), NotNil)
   244  }
   245  
   246  func (s *testSuiteP1) TestChangePumpAndDrainer(c *C) {
   247  	tk := testkit.NewTestKit(c, s.causetstore)
   248  	// change pump or drainer's state need connect to etcd
   249  	// so will meet error "URL scheme must be http, https, unix, or unixs: /tmp/milevadb"
   250  	err := tk.InterDircToErr("change pump to node_state ='paused' for node_id 'pump1'")
   251  	c.Assert(err, ErrorMatches, "URL scheme must be http, https, unix, or unixs.*")
   252  	err = tk.InterDircToErr("change drainer to node_state ='paused' for node_id 'drainer1'")
   253  	c.Assert(err, ErrorMatches, "URL scheme must be http, https, unix, or unixs.*")
   254  }
   255  
   256  func (s *testSuiteP1) TestLoadStats(c *C) {
   257  	tk := testkit.NewTestKit(c, s.causetstore)
   258  	tk.MustInterDirc("use test")
   259  	c.Assert(tk.InterDircToErr("load stats"), NotNil)
   260  	c.Assert(tk.InterDircToErr("load stats ./xxx.json"), NotNil)
   261  }
   262  
   263  func (s *testSuiteP1) TestShow(c *C) {
   264  	tk := testkit.NewTestKit(c, s.causetstore)
   265  	tk.MustInterDirc("create database test_show;")
   266  	tk.MustInterDirc("use test_show")
   267  
   268  	tk.MustQuery("show engines")
   269  	tk.MustInterDirc("drop causet if exists t")
   270  	tk.MustInterDirc("create causet t(a int primary key)")
   271  	c.Assert(len(tk.MustQuery("show index in t").Events()), Equals, 1)
   272  	c.Assert(len(tk.MustQuery("show index from t").Events()), Equals, 1)
   273  
   274  	tk.MustQuery("show charset").Check(testkit.Events(
   275  		"utf8 UTF-8 Unicode utf8_bin 3",
   276  		"utf8mb4 UTF-8 Unicode utf8mb4_bin 4",
   277  		"ascii US ASCII ascii_bin 1",
   278  		"latin1 Latin1 latin1_bin 1",
   279  		"binary binary binary 1"))
   280  	c.Assert(len(tk.MustQuery("show master status").Events()), Equals, 1)
   281  	tk.MustQuery("show create database test_show").Check(testkit.Events("test_show CREATE DATABASE `test_show` /*!40100 DEFAULT CHARACTER SET utf8mb4 */"))
   282  	tk.MustQuery("show privileges").Check(testkit.Events("Alter Blocks To alter the causet",
   283  		"Alter Blocks To alter the causet",
   284  		"Alter routine Functions,Procedures To alter or drop stored functions/procedures",
   285  		"Create Databases,Blocks,Indexes To create new databases and blocks",
   286  		"Create routine Databases To use CREATE FUNCTION/PROCEDURE",
   287  		"Create temporary blocks Databases To use CREATE TEMPORARY TABLE",
   288  		"Create view Blocks To create new views",
   289  		"Create user Server Admin To create new users",
   290  		"Delete Blocks To delete existing rows",
   291  		"Drop Databases,Blocks To drop databases, blocks, and views",
   292  		"Event Server Admin To create, alter, drop and execute events",
   293  		"InterDircute Functions,Procedures To execute stored routines",
   294  		"File File access on server To read and write files on the server",
   295  		"Grant option Databases,Blocks,Functions,Procedures To give to other users those privileges you possess",
   296  		"Index Blocks To create or drop indexes",
   297  		"Insert Blocks To insert data into blocks",
   298  		"Lock blocks Databases To use LOCK TABLES (together with SELECT privilege)",
   299  		"Process Server Admin To view the plain text of currently executing queries",
   300  		"Proxy Server Admin To make proxy user possible",
   301  		"References Databases,Blocks To have references on blocks",
   302  		"Reload Server Admin To reload or refresh blocks, logs and privileges",
   303  		"Replication client Server Admin To ask where the slave or master servers are",
   304  		"Replication slave Server Admin To read binary log events from the master",
   305  		"Select Blocks To retrieve rows from causet",
   306  		"Show databases Server Admin To see all databases with SHOW DATABASES",
   307  		"Show view Blocks To see views with SHOW CREATE VIEW",
   308  		"Shutdown Server Admin To shut down the server",
   309  		"Super Server Admin To use KILL thread, SET GLOBAL, CHANGE MASTER, etc.",
   310  		"Trigger Blocks To use triggers",
   311  		"Create blockspace Server Admin To create/alter/drop blockspaces",
   312  		"UFIDelate Blocks To uFIDelate existing rows",
   313  		"Usage Server Admin No privileges - allow connect only"))
   314  	c.Assert(len(tk.MustQuery("show causet status").Events()), Equals, 1)
   315  }
   316  
   317  func (s *testSuite3) TestAdmin(c *C) {
   318  	tk := testkit.NewTestKit(c, s.causetstore)
   319  	tk.MustInterDirc("use test")
   320  	tk.MustInterDirc("drop causet if exists admin_test")
   321  	tk.MustInterDirc("create causet admin_test (c1 int, c2 int, c3 int default 1, index (c1))")
   322  	tk.MustInterDirc("insert admin_test (c1) values (1),(2),(NULL)")
   323  
   324  	ctx := context.Background()
   325  	// cancel DBS jobs test
   326  	r, err := tk.InterDirc("admin cancel dbs jobs 1")
   327  	c.Assert(err, IsNil, Commentf("err %v", err))
   328  	req := r.NewChunk()
   329  	err = r.Next(ctx, req)
   330  	c.Assert(err, IsNil)
   331  	event := req.GetEvent(0)
   332  	c.Assert(event.Len(), Equals, 2)
   333  	c.Assert(event.GetString(0), Equals, "1")
   334  	c.Assert(event.GetString(1), Matches, "*DBS Job:1 not found")
   335  
   336  	// show dbs test;
   337  	r, err = tk.InterDirc("admin show dbs")
   338  	c.Assert(err, IsNil)
   339  	req = r.NewChunk()
   340  	err = r.Next(ctx, req)
   341  	c.Assert(err, IsNil)
   342  	event = req.GetEvent(0)
   343  	c.Assert(event.Len(), Equals, 6)
   344  	txn, err := s.causetstore.Begin()
   345  	c.Assert(err, IsNil)
   346  	dbsInfo, err := admin.GetDBSInfo(txn)
   347  	c.Assert(err, IsNil)
   348  	c.Assert(event.GetInt64(0), Equals, dbsInfo.SchemaVer)
   349  	// TODO: Pass this test.
   350  	// rowTenantInfos := strings.Split(event.Data[1].GetString(), ",")
   351  	// tenantInfos := strings.Split(dbsInfo.Tenant.String(), ",")
   352  	// c.Assert(rowTenantInfos[0], Equals, tenantInfos[0])
   353  	serverInfo, err := infosync.GetServerInfoByID(ctx, event.GetString(1))
   354  	c.Assert(err, IsNil)
   355  	c.Assert(event.GetString(2), Equals, serverInfo.IP+":"+
   356  		strconv.FormatUint(uint64(serverInfo.Port), 10))
   357  	c.Assert(event.GetString(3), Equals, "")
   358  	req = r.NewChunk()
   359  	err = r.Next(ctx, req)
   360  	c.Assert(err, IsNil)
   361  	c.Assert(req.NumEvents() == 0, IsTrue)
   362  	err = txn.Rollback()
   363  	c.Assert(err, IsNil)
   364  
   365  	// show DBS jobs test
   366  	r, err = tk.InterDirc("admin show dbs jobs")
   367  	c.Assert(err, IsNil)
   368  	req = r.NewChunk()
   369  	err = r.Next(ctx, req)
   370  	c.Assert(err, IsNil)
   371  	event = req.GetEvent(0)
   372  	c.Assert(event.Len(), Equals, 11)
   373  	txn, err = s.causetstore.Begin()
   374  	c.Assert(err, IsNil)
   375  	historyJobs, err := admin.GetHistoryDBSJobs(txn, admin.DefNumHistoryJobs)
   376  	c.Assert(len(historyJobs), Greater, 1)
   377  	c.Assert(len(event.GetString(1)), Greater, 0)
   378  	c.Assert(err, IsNil)
   379  	c.Assert(event.GetInt64(0), Equals, historyJobs[0].ID)
   380  	c.Assert(err, IsNil)
   381  
   382  	r, err = tk.InterDirc("admin show dbs jobs 20")
   383  	c.Assert(err, IsNil)
   384  	req = r.NewChunk()
   385  	err = r.Next(ctx, req)
   386  	c.Assert(err, IsNil)
   387  	event = req.GetEvent(0)
   388  	c.Assert(event.Len(), Equals, 11)
   389  	c.Assert(event.GetInt64(0), Equals, historyJobs[0].ID)
   390  	c.Assert(err, IsNil)
   391  
   392  	// show DBS job queries test
   393  	tk.MustInterDirc("use test")
   394  	tk.MustInterDirc("drop causet if exists admin_test2")
   395  	tk.MustInterDirc("create causet admin_test2 (c1 int, c2 int, c3 int default 1, index (c1))")
   396  	result := tk.MustQuery(`admin show dbs job queries 1, 1, 1`)
   397  	result.Check(testkit.Events())
   398  	result = tk.MustQuery(`admin show dbs job queries 1, 2, 3, 4`)
   399  	result.Check(testkit.Events())
   400  	historyJobs, err = admin.GetHistoryDBSJobs(txn, admin.DefNumHistoryJobs)
   401  	result = tk.MustQuery(fmt.Sprintf("admin show dbs job queries %d", historyJobs[0].ID))
   402  	result.Check(testkit.Events(historyJobs[0].Query))
   403  	c.Assert(err, IsNil)
   404  
   405  	// check causet test
   406  	tk.MustInterDirc("create causet admin_test1 (c1 int, c2 int default 1, index (c1))")
   407  	tk.MustInterDirc("insert admin_test1 (c1) values (21),(22)")
   408  	r, err = tk.InterDirc("admin check causet admin_test, admin_test1")
   409  	c.Assert(err, IsNil)
   410  	c.Assert(r, IsNil)
   411  	// error causet name
   412  	err = tk.InterDircToErr("admin check causet admin_test_error")
   413  	c.Assert(err, NotNil)
   414  	// different index values
   415  	sctx := tk.Se.(stochastikctx.Context)
   416  	dom := petri.GetPetri(sctx)
   417  	is := dom.SchemaReplicant()
   418  	c.Assert(is, NotNil)
   419  	tb, err := is.BlockByName(perceptron.NewCIStr("test"), perceptron.NewCIStr("admin_test"))
   420  	c.Assert(err, IsNil)
   421  	c.Assert(tb.Indices(), HasLen, 1)
   422  	_, err = tb.Indices()[0].Create(mock.NewContext(), txn.GetUnionStore(), types.MakeCausets(int64(10)), ekv.IntHandle(1))
   423  	c.Assert(err, IsNil)
   424  	err = txn.Commit(context.Background())
   425  	c.Assert(err, IsNil)
   426  	errAdmin := tk.InterDircToErr("admin check causet admin_test")
   427  	c.Assert(errAdmin, NotNil)
   428  
   429  	if config.CheckBlockBeforeDrop {
   430  		err = tk.InterDircToErr("drop causet admin_test")
   431  		c.Assert(err.Error(), Equals, errAdmin.Error())
   432  
   433  		// Drop inconsistency index.
   434  		tk.MustInterDirc("alter causet admin_test drop index c1")
   435  		tk.MustInterDirc("admin check causet admin_test")
   436  	}
   437  	// checksum causet test
   438  	tk.MustInterDirc("create causet checksum_with_index (id int, count int, PRIMARY KEY(id), KEY(count))")
   439  	tk.MustInterDirc("create causet checksum_without_index (id int, count int, PRIMARY KEY(id))")
   440  	r, err = tk.InterDirc("admin checksum causet checksum_with_index, checksum_without_index")
   441  	c.Assert(err, IsNil)
   442  	res := tk.ResultSetToResult(r, Commentf("admin checksum causet"))
   443  	// Mockeinsteindb returns 1 for every causet/index scan, then we will xor the checksums of a causet.
   444  	// For "checksum_with_index", we have two checksums, so the result will be 1^1 = 0.
   445  	// For "checksum_without_index", we only have one checksum, so the result will be 1.
   446  	res.Sort().Check(testkit.Events("test checksum_with_index 0 2 2", "test checksum_without_index 1 1 1"))
   447  
   448  	tk.MustInterDirc("drop causet if exists t1;")
   449  	tk.MustInterDirc("CREATE TABLE t1 (c2 BOOL, PRIMARY KEY (c2));")
   450  	tk.MustInterDirc("INSERT INTO t1 SET c2 = '0';")
   451  	tk.MustInterDirc("ALTER TABLE t1 ADD COLUMN c3 DATETIME NULL DEFAULT '2668-02-03 17:19:31';")
   452  	tk.MustInterDirc("ALTER TABLE t1 ADD INDEX idx2 (c3);")
   453  	tk.MustInterDirc("ALTER TABLE t1 ADD COLUMN c4 bit(10) default 127;")
   454  	tk.MustInterDirc("ALTER TABLE t1 ADD INDEX idx3 (c4);")
   455  	tk.MustInterDirc("admin check causet t1;")
   456  
   457  	// Test admin show dbs jobs causet name after causet has been droped.
   458  	tk.MustInterDirc("drop causet if exists t1;")
   459  	re := tk.MustQuery("admin show dbs jobs 1")
   460  	rows := re.Events()
   461  	c.Assert(len(rows), Equals, 1)
   462  	c.Assert(rows[0][2], Equals, "t1")
   463  
   464  	// Test for reverse scan get history dbs jobs when dbs history jobs queue has multiple regions.
   465  	txn, err = s.causetstore.Begin()
   466  	c.Assert(err, IsNil)
   467  	historyJobs, err = admin.GetHistoryDBSJobs(txn, 20)
   468  	c.Assert(err, IsNil)
   469  
   470  	// Split region for history dbs job queues.
   471  	m := spacetime.NewMeta(txn)
   472  	startKey := spacetime.DBSJobHistoryKey(m, 0)
   473  	endKey := spacetime.DBSJobHistoryKey(m, historyJobs[0].ID)
   474  	s.cluster.SplitKeys(startKey, endKey, int(historyJobs[0].ID/5))
   475  
   476  	historyJobs2, err := admin.GetHistoryDBSJobs(txn, 20)
   477  	c.Assert(err, IsNil)
   478  	c.Assert(historyJobs, DeepEquals, historyJobs2)
   479  }
   480  
   481  func (s *testSuiteP2) TestAdminShowDBSJobs(c *C) {
   482  	tk := testkit.NewTestKit(c, s.causetstore)
   483  	tk.MustInterDirc("create database if not exists test_admin_show_dbs_jobs")
   484  	tk.MustInterDirc("use test_admin_show_dbs_jobs")
   485  	tk.MustInterDirc("create causet t (a int);")
   486  
   487  	re := tk.MustQuery("admin show dbs jobs 1")
   488  	event := re.Events()[0]
   489  	c.Assert(event[1], Equals, "test_admin_show_dbs_jobs")
   490  	jobID, err := strconv.Atoi(event[0].(string))
   491  	c.Assert(err, IsNil)
   492  
   493  	err = ekv.RunInNewTxn(s.causetstore, true, func(txn ekv.Transaction) error {
   494  		t := spacetime.NewMeta(txn)
   495  		job, err := t.GetHistoryDBSJob(int64(jobID))
   496  		c.Assert(err, IsNil)
   497  		c.Assert(job, NotNil)
   498  		// Test for compatibility. Old MilevaDB version doesn't have SchemaName field, and the BinlogInfo maybe nil.
   499  		// See PR: 11561.
   500  		job.BinlogInfo = nil
   501  		job.SchemaName = ""
   502  		err = t.AddHistoryDBSJob(job, true)
   503  		c.Assert(err, IsNil)
   504  		return nil
   505  	})
   506  	c.Assert(err, IsNil)
   507  
   508  	re = tk.MustQuery("admin show dbs jobs 1")
   509  	event = re.Events()[0]
   510  	c.Assert(event[1], Equals, "test_admin_show_dbs_jobs")
   511  
   512  	re = tk.MustQuery("admin show dbs jobs 1 where job_type='create causet'")
   513  	event = re.Events()[0]
   514  	c.Assert(event[1], Equals, "test_admin_show_dbs_jobs")
   515  	c.Assert(event[9], Equals, "<nil>")
   516  
   517  	// Test the START_TIME and END_TIME field.
   518  	re = tk.MustQuery("admin show dbs jobs where job_type = 'create causet' and start_time > str_to_date('20190101','%Y%m%d%H%i%s')")
   519  	event = re.Events()[0]
   520  	c.Assert(event[2], Equals, "t")
   521  	c.Assert(event[9], Equals, "<nil>")
   522  }
   523  
   524  func (s *testSuiteP2) TestAdminChecksumOfPartitionedBlock(c *C) {
   525  	tk := testkit.NewTestKit(c, s.causetstore)
   526  	tk.MustInterDirc("USE test;")
   527  	tk.MustInterDirc("DROP TABLE IF EXISTS admin_checksum_partition_test;")
   528  	tk.MustInterDirc("CREATE TABLE admin_checksum_partition_test (a INT) PARTITION BY HASH(a) PARTITIONS 4;")
   529  	tk.MustInterDirc("INSERT INTO admin_checksum_partition_test VALUES (1), (2);")
   530  
   531  	r := tk.MustQuery("ADMIN CHECKSUM TABLE admin_checksum_partition_test;")
   532  	r.Check(testkit.Events("test admin_checksum_partition_test 1 5 5"))
   533  }
   534  
   535  func (s *baseTestSuite) fillData(tk *testkit.TestKit, causet string) {
   536  	tk.MustInterDirc("use test")
   537  	tk.MustInterDirc(fmt.Sprintf("create causet %s(id int not null default 1, name varchar(255), PRIMARY KEY(id));", causet))
   538  
   539  	// insert data
   540  	tk.MustInterDirc(fmt.Sprintf("insert INTO %s VALUES (1, \"hello\");", causet))
   541  	tk.CheckInterDircResult(1, 0)
   542  	tk.MustInterDirc(fmt.Sprintf("insert into %s values (2, \"hello\");", causet))
   543  	tk.CheckInterDircResult(1, 0)
   544  }
   545  
   546  type testCase struct {
   547  	data1       []byte
   548  	data2       []byte
   549  	expected    []string
   550  	restData    []byte
   551  	expectedMsg string
   552  }
   553  
   554  func checkCases(tests []testCase, ld *interlock.LoadDataInfo,
   555  	c *C, tk *testkit.TestKit, ctx stochastikctx.Context, selectALLEGROSQL, deleteALLEGROSQL string) {
   556  	origin := ld.IgnoreLines
   557  	for _, tt := range tests {
   558  		ld.IgnoreLines = origin
   559  		c.Assert(ctx.NewTxn(context.Background()), IsNil)
   560  		ctx.GetStochastikVars().StmtCtx.DupKeyAsWarning = true
   561  		ctx.GetStochastikVars().StmtCtx.BadNullAsWarning = true
   562  		ctx.GetStochastikVars().StmtCtx.InLoadDataStmt = true
   563  		ctx.GetStochastikVars().StmtCtx.InDeleteStmt = false
   564  		data, reachLimit, err1 := ld.InsertData(context.Background(), tt.data1, tt.data2)
   565  		c.Assert(err1, IsNil)
   566  		c.Assert(reachLimit, IsFalse)
   567  		err1 = ld.CheckAndInsertOneBatch(context.Background(), ld.GetEvents(), ld.GetCurBatchCnt())
   568  		c.Assert(err1, IsNil)
   569  		ld.SetMaxEventsInBatch(20000)
   570  		if tt.restData == nil {
   571  			c.Assert(data, HasLen, 0,
   572  				Commentf("data1:%v, data2:%v, data:%v", string(tt.data1), string(tt.data2), string(data)))
   573  		} else {
   574  			c.Assert(data, DeepEquals, tt.restData,
   575  				Commentf("data1:%v, data2:%v, data:%v", string(tt.data1), string(tt.data2), string(data)))
   576  		}
   577  		ld.SetMessage()
   578  		tk.CheckLastMessage(tt.expectedMsg)
   579  		ctx.StmtCommit()
   580  		txn, err := ctx.Txn(true)
   581  		c.Assert(err, IsNil)
   582  		err = txn.Commit(context.Background())
   583  		c.Assert(err, IsNil)
   584  		r := tk.MustQuery(selectALLEGROSQL)
   585  		r.Check(solitonutil.EventsWithSep("|", tt.expected...))
   586  		tk.MustInterDirc(deleteALLEGROSQL)
   587  	}
   588  }
   589  
   590  func (s *testSuiteP1) TestSelectWithoutFrom(c *C) {
   591  	tk := testkit.NewTestKit(c, s.causetstore)
   592  	tk.MustInterDirc("use test")
   593  
   594  	r := tk.MustQuery("select 1 + 2*3;")
   595  	r.Check(testkit.Events("7"))
   596  
   597  	r = tk.MustQuery(`select _utf8"string";`)
   598  	r.Check(testkit.Events("string"))
   599  
   600  	r = tk.MustQuery("select 1 order by 1;")
   601  	r.Check(testkit.Events("1"))
   602  }
   603  
   604  // TestSelectBackslashN Issue 3685.
   605  func (s *testSuiteP1) TestSelectBackslashN(c *C) {
   606  	tk := testkit.NewTestKit(c, s.causetstore)
   607  
   608  	allegrosql := `select \N;`
   609  	r := tk.MustQuery(allegrosql)
   610  	r.Check(testkit.Events("<nil>"))
   611  	rs, err := tk.InterDirc(allegrosql)
   612  	c.Check(err, IsNil)
   613  	fields := rs.Fields()
   614  	c.Check(len(fields), Equals, 1)
   615  	c.Check(fields[0].DeferredCauset.Name.O, Equals, "NULL")
   616  
   617  	allegrosql = `select "\N";`
   618  	r = tk.MustQuery(allegrosql)
   619  	r.Check(testkit.Events("N"))
   620  	rs, err = tk.InterDirc(allegrosql)
   621  	c.Check(err, IsNil)
   622  	fields = rs.Fields()
   623  	c.Check(len(fields), Equals, 1)
   624  	c.Check(fields[0].DeferredCauset.Name.O, Equals, `N`)
   625  
   626  	tk.MustInterDirc("use test;")
   627  	tk.MustInterDirc("create causet test (`\\N` int);")
   628  	tk.MustInterDirc("insert into test values (1);")
   629  	tk.CheckInterDircResult(1, 0)
   630  	allegrosql = "select * from test;"
   631  	r = tk.MustQuery(allegrosql)
   632  	r.Check(testkit.Events("1"))
   633  	rs, err = tk.InterDirc(allegrosql)
   634  	c.Check(err, IsNil)
   635  	fields = rs.Fields()
   636  	c.Check(len(fields), Equals, 1)
   637  	c.Check(fields[0].DeferredCauset.Name.O, Equals, `\N`)
   638  
   639  	allegrosql = `select \N from test;`
   640  	r = tk.MustQuery(allegrosql)
   641  	r.Check(testkit.Events("<nil>"))
   642  	rs, err = tk.InterDirc(allegrosql)
   643  	c.Check(err, IsNil)
   644  	fields = rs.Fields()
   645  	c.Check(err, IsNil)
   646  	c.Check(len(fields), Equals, 1)
   647  	c.Check(fields[0].DeferredCauset.Name.O, Equals, `NULL`)
   648  
   649  	allegrosql = `select (\N) from test;`
   650  	r = tk.MustQuery(allegrosql)
   651  	r.Check(testkit.Events("<nil>"))
   652  	rs, err = tk.InterDirc(allegrosql)
   653  	c.Check(err, IsNil)
   654  	fields = rs.Fields()
   655  	c.Check(len(fields), Equals, 1)
   656  	c.Check(fields[0].DeferredCauset.Name.O, Equals, `NULL`)
   657  
   658  	allegrosql = "select `\\N` from test;"
   659  	r = tk.MustQuery(allegrosql)
   660  	r.Check(testkit.Events("1"))
   661  	rs, err = tk.InterDirc(allegrosql)
   662  	c.Check(err, IsNil)
   663  	fields = rs.Fields()
   664  	c.Check(len(fields), Equals, 1)
   665  	c.Check(fields[0].DeferredCauset.Name.O, Equals, `\N`)
   666  
   667  	allegrosql = "select (`\\N`) from test;"
   668  	r = tk.MustQuery(allegrosql)
   669  	r.Check(testkit.Events("1"))
   670  	rs, err = tk.InterDirc(allegrosql)
   671  	c.Check(err, IsNil)
   672  	fields = rs.Fields()
   673  	c.Check(len(fields), Equals, 1)
   674  	c.Check(fields[0].DeferredCauset.Name.O, Equals, `\N`)
   675  
   676  	allegrosql = `select '\N' from test;`
   677  	r = tk.MustQuery(allegrosql)
   678  	r.Check(testkit.Events("N"))
   679  	rs, err = tk.InterDirc(allegrosql)
   680  	c.Check(err, IsNil)
   681  	fields = rs.Fields()
   682  	c.Check(len(fields), Equals, 1)
   683  	c.Check(fields[0].DeferredCauset.Name.O, Equals, `N`)
   684  
   685  	allegrosql = `select ('\N') from test;`
   686  	r = tk.MustQuery(allegrosql)
   687  	r.Check(testkit.Events("N"))
   688  	rs, err = tk.InterDirc(allegrosql)
   689  	c.Check(err, IsNil)
   690  	fields = rs.Fields()
   691  	c.Check(len(fields), Equals, 1)
   692  	c.Check(fields[0].DeferredCauset.Name.O, Equals, `N`)
   693  }
   694  
   695  // TestSelectNull Issue #4053.
   696  func (s *testSuiteP1) TestSelectNull(c *C) {
   697  	tk := testkit.NewTestKit(c, s.causetstore)
   698  
   699  	allegrosql := `select nUll;`
   700  	r := tk.MustQuery(allegrosql)
   701  	r.Check(testkit.Events("<nil>"))
   702  	rs, err := tk.InterDirc(allegrosql)
   703  	c.Check(err, IsNil)
   704  	fields := rs.Fields()
   705  	c.Check(len(fields), Equals, 1)
   706  	c.Check(fields[0].DeferredCauset.Name.O, Equals, `NULL`)
   707  
   708  	allegrosql = `select (null);`
   709  	r = tk.MustQuery(allegrosql)
   710  	r.Check(testkit.Events("<nil>"))
   711  	rs, err = tk.InterDirc(allegrosql)
   712  	c.Check(err, IsNil)
   713  	fields = rs.Fields()
   714  	c.Check(len(fields), Equals, 1)
   715  	c.Check(fields[0].DeferredCauset.Name.O, Equals, `NULL`)
   716  
   717  	allegrosql = `select null+NULL;`
   718  	r = tk.MustQuery(allegrosql)
   719  	r.Check(testkit.Events("<nil>"))
   720  	rs, err = tk.InterDirc(allegrosql)
   721  	c.Check(err, IsNil)
   722  	fields = rs.Fields()
   723  	c.Check(err, IsNil)
   724  	c.Check(len(fields), Equals, 1)
   725  	c.Check(fields[0].DeferredCauset.Name.O, Equals, `null+NULL`)
   726  }
   727  
   728  // TestSelectStringLiteral Issue #3686.
   729  func (s *testSuiteP1) TestSelectStringLiteral(c *C) {
   730  	tk := testkit.NewTestKit(c, s.causetstore)
   731  
   732  	allegrosql := `select 'abc';`
   733  	r := tk.MustQuery(allegrosql)
   734  	r.Check(testkit.Events("abc"))
   735  	rs, err := tk.InterDirc(allegrosql)
   736  	c.Check(err, IsNil)
   737  	fields := rs.Fields()
   738  	c.Check(len(fields), Equals, 1)
   739  	c.Check(fields[0].DeferredCauset.Name.O, Equals, `abc`)
   740  
   741  	allegrosql = `select (('abc'));`
   742  	r = tk.MustQuery(allegrosql)
   743  	r.Check(testkit.Events("abc"))
   744  	rs, err = tk.InterDirc(allegrosql)
   745  	c.Check(err, IsNil)
   746  	fields = rs.Fields()
   747  	c.Check(len(fields), Equals, 1)
   748  	c.Check(fields[0].DeferredCauset.Name.O, Equals, `abc`)
   749  
   750  	allegrosql = `select 'abc'+'def';`
   751  	r = tk.MustQuery(allegrosql)
   752  	r.Check(testkit.Events("0"))
   753  	rs, err = tk.InterDirc(allegrosql)
   754  	c.Check(err, IsNil)
   755  	fields = rs.Fields()
   756  	c.Check(len(fields), Equals, 1)
   757  	c.Check(fields[0].DeferredCauset.Name.O, Equals, `'abc'+'def'`)
   758  
   759  	// Below checks whether leading invalid chars are trimmed.
   760  	allegrosql = "select '\n';"
   761  	r = tk.MustQuery(allegrosql)
   762  	r.Check(testkit.Events("\n"))
   763  	rs, err = tk.InterDirc(allegrosql)
   764  	c.Check(err, IsNil)
   765  	fields = rs.Fields()
   766  	c.Check(len(fields), Equals, 1)
   767  	c.Check(fields[0].DeferredCauset.Name.O, Equals, "")
   768  
   769  	allegrosql = "select '\t   defCaus';" // Lowercased letter is a valid char.
   770  	rs, err = tk.InterDirc(allegrosql)
   771  	c.Check(err, IsNil)
   772  	fields = rs.Fields()
   773  	c.Check(len(fields), Equals, 1)
   774  	c.Check(fields[0].DeferredCauset.Name.O, Equals, "defCaus")
   775  
   776  	allegrosql = "select '\t   DefCaus';" // Uppercased letter is a valid char.
   777  	rs, err = tk.InterDirc(allegrosql)
   778  	c.Check(err, IsNil)
   779  	fields = rs.Fields()
   780  	c.Check(len(fields), Equals, 1)
   781  	c.Check(fields[0].DeferredCauset.Name.O, Equals, "DefCaus")
   782  
   783  	allegrosql = "select '\n\t   中文 defCaus';" // Chinese char is a valid char.
   784  	rs, err = tk.InterDirc(allegrosql)
   785  	c.Check(err, IsNil)
   786  	fields = rs.Fields()
   787  	c.Check(len(fields), Equals, 1)
   788  	c.Check(fields[0].DeferredCauset.Name.O, Equals, "中文 defCaus")
   789  
   790  	allegrosql = "select ' \r\n  .defCaus';" // Punctuation is a valid char.
   791  	rs, err = tk.InterDirc(allegrosql)
   792  	c.Check(err, IsNil)
   793  	fields = rs.Fields()
   794  	c.Check(len(fields), Equals, 1)
   795  	c.Check(fields[0].DeferredCauset.Name.O, Equals, ".defCaus")
   796  
   797  	allegrosql = "select '   😆defCaus';" // Emoji is a valid char.
   798  	rs, err = tk.InterDirc(allegrosql)
   799  	c.Check(err, IsNil)
   800  	fields = rs.Fields()
   801  	c.Check(len(fields), Equals, 1)
   802  	c.Check(fields[0].DeferredCauset.Name.O, Equals, "😆defCaus")
   803  
   804  	// Below checks whether trailing invalid chars are preserved.
   805  	allegrosql = `select 'abc   ';`
   806  	rs, err = tk.InterDirc(allegrosql)
   807  	c.Check(err, IsNil)
   808  	fields = rs.Fields()
   809  	c.Check(len(fields), Equals, 1)
   810  	c.Check(fields[0].DeferredCauset.Name.O, Equals, "abc   ")
   811  
   812  	allegrosql = `select '  abc   123   ';`
   813  	rs, err = tk.InterDirc(allegrosql)
   814  	c.Check(err, IsNil)
   815  	fields = rs.Fields()
   816  	c.Check(len(fields), Equals, 1)
   817  	c.Check(fields[0].DeferredCauset.Name.O, Equals, "abc   123   ")
   818  
   819  	// Issue #4239.
   820  	allegrosql = `select 'a' ' ' 'string';`
   821  	r = tk.MustQuery(allegrosql)
   822  	r.Check(testkit.Events("a string"))
   823  	rs, err = tk.InterDirc(allegrosql)
   824  	c.Check(err, IsNil)
   825  	fields = rs.Fields()
   826  	c.Check(len(fields), Equals, 1)
   827  	c.Check(fields[0].DeferredCauset.Name.O, Equals, "a")
   828  
   829  	allegrosql = `select 'a' " " "string";`
   830  	r = tk.MustQuery(allegrosql)
   831  	r.Check(testkit.Events("a string"))
   832  	rs, err = tk.InterDirc(allegrosql)
   833  	c.Check(err, IsNil)
   834  	fields = rs.Fields()
   835  	c.Check(len(fields), Equals, 1)
   836  	c.Check(fields[0].DeferredCauset.Name.O, Equals, "a")
   837  
   838  	allegrosql = `select 'string' 'string';`
   839  	r = tk.MustQuery(allegrosql)
   840  	r.Check(testkit.Events("stringstring"))
   841  	rs, err = tk.InterDirc(allegrosql)
   842  	c.Check(err, IsNil)
   843  	fields = rs.Fields()
   844  	c.Check(len(fields), Equals, 1)
   845  	c.Check(fields[0].DeferredCauset.Name.O, Equals, "string")
   846  
   847  	allegrosql = `select "ss" "a";`
   848  	r = tk.MustQuery(allegrosql)
   849  	r.Check(testkit.Events("ssa"))
   850  	rs, err = tk.InterDirc(allegrosql)
   851  	c.Check(err, IsNil)
   852  	fields = rs.Fields()
   853  	c.Check(len(fields), Equals, 1)
   854  	c.Check(fields[0].DeferredCauset.Name.O, Equals, "ss")
   855  
   856  	allegrosql = `select "ss" "a" "b";`
   857  	r = tk.MustQuery(allegrosql)
   858  	r.Check(testkit.Events("ssab"))
   859  	rs, err = tk.InterDirc(allegrosql)
   860  	c.Check(err, IsNil)
   861  	fields = rs.Fields()
   862  	c.Check(len(fields), Equals, 1)
   863  	c.Check(fields[0].DeferredCauset.Name.O, Equals, "ss")
   864  
   865  	allegrosql = `select "ss" "a" ' ' "b";`
   866  	r = tk.MustQuery(allegrosql)
   867  	r.Check(testkit.Events("ssa b"))
   868  	rs, err = tk.InterDirc(allegrosql)
   869  	c.Check(err, IsNil)
   870  	fields = rs.Fields()
   871  	c.Check(len(fields), Equals, 1)
   872  	c.Check(fields[0].DeferredCauset.Name.O, Equals, "ss")
   873  
   874  	allegrosql = `select "ss" "a" ' ' "b" ' ' "d";`
   875  	r = tk.MustQuery(allegrosql)
   876  	r.Check(testkit.Events("ssa b d"))
   877  	rs, err = tk.InterDirc(allegrosql)
   878  	c.Check(err, IsNil)
   879  	fields = rs.Fields()
   880  	c.Check(len(fields), Equals, 1)
   881  	c.Check(fields[0].DeferredCauset.Name.O, Equals, "ss")
   882  }
   883  
   884  func (s *testSuiteP1) TestSelectLimit(c *C) {
   885  	tk := testkit.NewTestKit(c, s.causetstore)
   886  	tk.MustInterDirc("use test")
   887  	s.fillData(tk, "select_limit")
   888  
   889  	tk.MustInterDirc("insert INTO select_limit VALUES (3, \"hello\");")
   890  	tk.CheckInterDircResult(1, 0)
   891  	tk.MustInterDirc("insert INTO select_limit VALUES (4, \"hello\");")
   892  	tk.CheckInterDircResult(1, 0)
   893  
   894  	r := tk.MustQuery("select * from select_limit limit 1;")
   895  	r.Check(testkit.Events("1 hello"))
   896  
   897  	r = tk.MustQuery("select id from (select * from select_limit limit 1) k where id != 1;")
   898  	r.Check(testkit.Events())
   899  
   900  	r = tk.MustQuery("select * from select_limit limit 18446744073709551615 offset 0;")
   901  	r.Check(testkit.Events("1 hello", "2 hello", "3 hello", "4 hello"))
   902  
   903  	r = tk.MustQuery("select * from select_limit limit 18446744073709551615 offset 1;")
   904  	r.Check(testkit.Events("2 hello", "3 hello", "4 hello"))
   905  
   906  	r = tk.MustQuery("select * from select_limit limit 18446744073709551615 offset 3;")
   907  	r.Check(testkit.Events("4 hello"))
   908  
   909  	err := tk.InterDircToErr("select * from select_limit limit 18446744073709551616 offset 3;")
   910  	c.Assert(err, NotNil)
   911  }
   912  
   913  func (s *testSuiteP1) TestSelectOrderBy(c *C) {
   914  	tk := testkit.NewTestKit(c, s.causetstore)
   915  	tk.MustInterDirc("use test")
   916  	s.fillData(tk, "select_order_test")
   917  
   918  	// Test star field
   919  	r := tk.MustQuery("select * from select_order_test where id = 1 order by id limit 1 offset 0;")
   920  	r.Check(testkit.Events("1 hello"))
   921  
   922  	r = tk.MustQuery("select id from select_order_test order by id desc limit 1 ")
   923  	r.Check(testkit.Events("2"))
   924  
   925  	r = tk.MustQuery("select id from select_order_test order by id + 1 desc limit 1 ")
   926  	r.Check(testkit.Events("2"))
   927  
   928  	// Test limit
   929  	r = tk.MustQuery("select * from select_order_test order by name, id limit 1 offset 0;")
   930  	r.Check(testkit.Events("1 hello"))
   931  
   932  	// Test limit
   933  	r = tk.MustQuery("select id as c1, name from select_order_test order by 2, id limit 1 offset 0;")
   934  	r.Check(testkit.Events("1 hello"))
   935  
   936  	// Test limit overflow
   937  	r = tk.MustQuery("select * from select_order_test order by name, id limit 100 offset 0;")
   938  	r.Check(testkit.Events("1 hello", "2 hello"))
   939  
   940  	// Test offset overflow
   941  	r = tk.MustQuery("select * from select_order_test order by name, id limit 1 offset 100;")
   942  	r.Check(testkit.Events())
   943  
   944  	// Test limit exceeds int range.
   945  	r = tk.MustQuery("select id from select_order_test order by name, id limit 18446744073709551615;")
   946  	r.Check(testkit.Events("1", "2"))
   947  
   948  	// Test multiple field
   949  	r = tk.MustQuery("select id, name from select_order_test where id = 1 group by id, name limit 1 offset 0;")
   950  	r.Check(testkit.Events("1 hello"))
   951  
   952  	// Test limit + order by
   953  	for i := 3; i <= 10; i += 1 {
   954  		tk.MustInterDirc(fmt.Sprintf("insert INTO select_order_test VALUES (%d, \"zz\");", i))
   955  	}
   956  	tk.MustInterDirc("insert INTO select_order_test VALUES (10086, \"hi\");")
   957  	for i := 11; i <= 20; i += 1 {
   958  		tk.MustInterDirc(fmt.Sprintf("insert INTO select_order_test VALUES (%d, \"hh\");", i))
   959  	}
   960  	for i := 21; i <= 30; i += 1 {
   961  		tk.MustInterDirc(fmt.Sprintf("insert INTO select_order_test VALUES (%d, \"zz\");", i))
   962  	}
   963  	tk.MustInterDirc("insert INTO select_order_test VALUES (1501, \"aa\");")
   964  	r = tk.MustQuery("select * from select_order_test order by name, id limit 1 offset 3;")
   965  	r.Check(testkit.Events("11 hh"))
   966  	tk.MustInterDirc("drop causet select_order_test")
   967  	tk.MustInterDirc("drop causet if exists t")
   968  	tk.MustInterDirc("create causet t (c int, d int)")
   969  	tk.MustInterDirc("insert t values (1, 1)")
   970  	tk.MustInterDirc("insert t values (1, 2)")
   971  	tk.MustInterDirc("insert t values (1, 3)")
   972  	r = tk.MustQuery("select 1-d as d from t order by d;")
   973  	r.Check(testkit.Events("-2", "-1", "0"))
   974  	r = tk.MustQuery("select 1-d as d from t order by d + 1;")
   975  	r.Check(testkit.Events("0", "-1", "-2"))
   976  	r = tk.MustQuery("select t.d from t order by d;")
   977  	r.Check(testkit.Events("1", "2", "3"))
   978  
   979  	tk.MustInterDirc("drop causet if exists t")
   980  	tk.MustInterDirc("create causet t (a int, b int, c int)")
   981  	tk.MustInterDirc("insert t values (1, 2, 3)")
   982  	r = tk.MustQuery("select b from (select a,b from t order by a,c) t")
   983  	r.Check(testkit.Events("2"))
   984  	r = tk.MustQuery("select b from (select a,b from t order by a,c limit 1) t")
   985  	r.Check(testkit.Events("2"))
   986  	tk.MustInterDirc("drop causet if exists t")
   987  	tk.MustInterDirc("create causet t(a int, b int, index idx(a))")
   988  	tk.MustInterDirc("insert into t values(1, 1), (2, 2)")
   989  	tk.MustQuery("select * from t where 1 order by b").Check(testkit.Events("1 1", "2 2"))
   990  	tk.MustQuery("select * from t where a between 1 and 2 order by a desc").Check(testkit.Events("2 2", "1 1"))
   991  
   992  	// Test double read and topN is pushed down to first read causetembedded.
   993  	tk.MustInterDirc("drop causet if exists t")
   994  	tk.MustInterDirc("create causet t(a int primary key, b int, c int, index idx(b))")
   995  	tk.MustInterDirc("insert into t values(1, 3, 1)")
   996  	tk.MustInterDirc("insert into t values(2, 2, 2)")
   997  	tk.MustInterDirc("insert into t values(3, 1, 3)")
   998  	tk.MustQuery("select * from t use index(idx) order by a desc limit 1").Check(testkit.Events("3 1 3"))
   999  
  1000  	// Test double read which needs to keep order.
  1001  	tk.MustInterDirc("drop causet if exists t")
  1002  	tk.MustInterDirc("create causet t(a int, b int, key b (b))")
  1003  	tk.Se.GetStochastikVars().IndexLookupSize = 3
  1004  	for i := 0; i < 10; i++ {
  1005  		tk.MustInterDirc(fmt.Sprintf("insert into t values(%d, %d)", i, 10-i))
  1006  	}
  1007  	tk.MustQuery("select a from t use index(b) order by b").Check(testkit.Events("9", "8", "7", "6", "5", "4", "3", "2", "1", "0"))
  1008  }
  1009  
  1010  func (s *testSuiteP1) TestOrderBy(c *C) {
  1011  	tk := testkit.NewTestKitWithInit(c, s.causetstore)
  1012  	tk.MustInterDirc("drop causet if exists t")
  1013  	tk.MustInterDirc("create causet t (c1 int, c2 int, c3 varchar(20))")
  1014  	tk.MustInterDirc("insert into t values (1, 2, 'abc'), (2, 1, 'bcd')")
  1015  
  1016  	// Fix issue https://github.com/whtcorpsinc/milevadb/issues/337
  1017  	tk.MustQuery("select c1 as a, c1 as b from t order by c1").Check(testkit.Events("1 1", "2 2"))
  1018  
  1019  	tk.MustQuery("select c1 as a, t.c1 as a from t order by a desc").Check(testkit.Events("2 2", "1 1"))
  1020  	tk.MustQuery("select c1 as c2 from t order by c2").Check(testkit.Events("1", "2"))
  1021  	tk.MustQuery("select sum(c1) from t order by sum(c1)").Check(testkit.Events("3"))
  1022  	tk.MustQuery("select c1 as c2 from t order by c2 + 1").Check(testkit.Events("2", "1"))
  1023  
  1024  	// Order by position.
  1025  	tk.MustQuery("select * from t order by 1").Check(testkit.Events("1 2 abc", "2 1 bcd"))
  1026  	tk.MustQuery("select * from t order by 2").Check(testkit.Events("2 1 bcd", "1 2 abc"))
  1027  
  1028  	// Order by binary.
  1029  	tk.MustQuery("select c1, c3 from t order by binary c1 desc").Check(testkit.Events("2 bcd", "1 abc"))
  1030  	tk.MustQuery("select c1, c2 from t order by binary c3").Check(testkit.Events("1 2", "2 1"))
  1031  }
  1032  
  1033  func (s *testSuiteP1) TestSelectErrorEvent(c *C) {
  1034  	tk := testkit.NewTestKit(c, s.causetstore)
  1035  	tk.MustInterDirc("use test")
  1036  
  1037  	err := tk.InterDircToErr("select event(1, 1) from test")
  1038  	c.Assert(err, NotNil)
  1039  
  1040  	err = tk.InterDircToErr("select * from test group by event(1, 1);")
  1041  	c.Assert(err, NotNil)
  1042  
  1043  	err = tk.InterDircToErr("select * from test order by event(1, 1);")
  1044  	c.Assert(err, NotNil)
  1045  
  1046  	err = tk.InterDircToErr("select * from test having event(1, 1);")
  1047  	c.Assert(err, NotNil)
  1048  
  1049  	err = tk.InterDircToErr("select (select 1, 1) from test;")
  1050  	c.Assert(err, NotNil)
  1051  
  1052  	err = tk.InterDircToErr("select * from test group by (select 1, 1);")
  1053  	c.Assert(err, NotNil)
  1054  
  1055  	err = tk.InterDircToErr("select * from test order by (select 1, 1);")
  1056  	c.Assert(err, NotNil)
  1057  
  1058  	err = tk.InterDircToErr("select * from test having (select 1, 1);")
  1059  	c.Assert(err, NotNil)
  1060  }
  1061  
  1062  // TestIssue2612 is related with https://github.com/whtcorpsinc/milevadb/issues/2612
  1063  func (s *testSuiteP1) TestIssue2612(c *C) {
  1064  	tk := testkit.NewTestKit(c, s.causetstore)
  1065  	tk.MustInterDirc("use test")
  1066  	tk.MustInterDirc(`drop causet if exists t`)
  1067  	tk.MustInterDirc(`create causet t (
  1068  		create_at datetime NOT NULL DEFAULT '1000-01-01 00:00:00',
  1069  		finish_at datetime NOT NULL DEFAULT '1000-01-01 00:00:00');`)
  1070  	tk.MustInterDirc(`insert into t values ('2020-02-13 15:32:24',  '2020-02-11 17:23:22');`)
  1071  	rs, err := tk.InterDirc(`select timediff(finish_at, create_at) from t;`)
  1072  	c.Assert(err, IsNil)
  1073  	req := rs.NewChunk()
  1074  	err = rs.Next(context.Background(), req)
  1075  	c.Assert(err, IsNil)
  1076  	c.Assert(req.GetEvent(0).GetDuration(0, 0).String(), Equals, "-46:09:02")
  1077  	rs.Close()
  1078  }
  1079  
  1080  // TestIssue345 is related with https://github.com/whtcorpsinc/milevadb/issues/345
  1081  func (s *testSuiteP1) TestIssue345(c *C) {
  1082  	tk := testkit.NewTestKit(c, s.causetstore)
  1083  	tk.MustInterDirc("use test")
  1084  	tk.MustInterDirc(`drop causet if exists t1, t2`)
  1085  	tk.MustInterDirc(`create causet t1 (c1 int);`)
  1086  	tk.MustInterDirc(`create causet t2 (c2 int);`)
  1087  	tk.MustInterDirc(`insert into t1 values (1);`)
  1088  	tk.MustInterDirc(`insert into t2 values (2);`)
  1089  	tk.MustInterDirc(`uFIDelate t1, t2 set t1.c1 = 2, t2.c2 = 1;`)
  1090  	tk.MustInterDirc(`uFIDelate t1, t2 set c1 = 2, c2 = 1;`)
  1091  	tk.MustInterDirc(`uFIDelate t1 as a, t2 as b set a.c1 = 2, b.c2 = 1;`)
  1092  
  1093  	// Check t1 content
  1094  	r := tk.MustQuery("SELECT * FROM t1;")
  1095  	r.Check(testkit.Events("2"))
  1096  	// Check t2 content
  1097  	r = tk.MustQuery("SELECT * FROM t2;")
  1098  	r.Check(testkit.Events("1"))
  1099  
  1100  	tk.MustInterDirc(`uFIDelate t1 as a, t2 as t1 set a.c1 = 1, t1.c2 = 2;`)
  1101  	// Check t1 content
  1102  	r = tk.MustQuery("SELECT * FROM t1;")
  1103  	r.Check(testkit.Events("1"))
  1104  	// Check t2 content
  1105  	r = tk.MustQuery("SELECT * FROM t2;")
  1106  	r.Check(testkit.Events("2"))
  1107  
  1108  	_, err := tk.InterDirc(`uFIDelate t1 as a, t2 set t1.c1 = 10;`)
  1109  	c.Assert(err, NotNil)
  1110  }
  1111  
  1112  func (s *testSuiteP1) TestIssue5055(c *C) {
  1113  	tk := testkit.NewTestKit(c, s.causetstore)
  1114  	tk.MustInterDirc("use test")
  1115  	tk.MustInterDirc(`drop causet if exists t1, t2`)
  1116  	tk.MustInterDirc(`create causet t1 (a int);`)
  1117  	tk.MustInterDirc(`create causet t2 (a int);`)
  1118  	tk.MustInterDirc(`insert into t1 values(1);`)
  1119  	tk.MustInterDirc(`insert into t2 values(1);`)
  1120  	result := tk.MustQuery("select tbl1.* from (select t1.a, 1 from t1) tbl1 left join t2 tbl2 on tbl1.a = tbl2.a order by tbl1.a desc limit 1;")
  1121  	result.Check(testkit.Events("1 1"))
  1122  }
  1123  
  1124  func (s *testSuiteWithData) TestSetOperation(c *C) {
  1125  	tk := testkit.NewTestKit(c, s.causetstore)
  1126  	tk.MustInterDirc(`use test`)
  1127  	tk.MustInterDirc(`drop causet if exists t1, t2, t3`)
  1128  	tk.MustInterDirc(`create causet t1(a int)`)
  1129  	tk.MustInterDirc(`create causet t2 like t1`)
  1130  	tk.MustInterDirc(`create causet t3 like t1`)
  1131  	tk.MustInterDirc(`insert into t1 values (1),(1),(2),(3),(null)`)
  1132  	tk.MustInterDirc(`insert into t2 values (1),(2),(null),(null)`)
  1133  	tk.MustInterDirc(`insert into t3 values (2),(3)`)
  1134  
  1135  	var input []string
  1136  	var output []struct {
  1137  		ALLEGROALLEGROSQL string
  1138  		Causet            []string
  1139  		Res               []string
  1140  	}
  1141  	s.testData.GetTestCases(c, &input, &output)
  1142  	for i, tt := range input {
  1143  		s.testData.OnRecord(func() {
  1144  			output[i].ALLEGROALLEGROSQL = tt
  1145  			output[i].Causet = s.testData.ConvertEventsToStrings(tk.MustQuery("explain " + tt).Events())
  1146  			output[i].Res = s.testData.ConvertEventsToStrings(tk.MustQuery(tt).Sort().Events())
  1147  		})
  1148  		tk.MustQuery("explain " + tt).Check(testkit.Events(output[i].Causet...))
  1149  		tk.MustQuery(tt).Sort().Check(testkit.Events(output[i].Res...))
  1150  	}
  1151  }
  1152  
  1153  func (s *testSuiteWithData) TestSetOperationOnDiffDefCausType(c *C) {
  1154  	tk := testkit.NewTestKit(c, s.causetstore)
  1155  	tk.MustInterDirc(`use test`)
  1156  	tk.MustInterDirc(`drop causet if exists t1, t2, t3`)
  1157  	tk.MustInterDirc(`create causet t1(a int, b int)`)
  1158  	tk.MustInterDirc(`create causet t2(a int, b varchar(20))`)
  1159  	tk.MustInterDirc(`create causet t3(a int, b decimal(30,10))`)
  1160  	tk.MustInterDirc(`insert into t1 values (1,1),(1,1),(2,2),(3,3),(null,null)`)
  1161  	tk.MustInterDirc(`insert into t2 values (1,'1'),(2,'2'),(null,null),(null,'3')`)
  1162  	tk.MustInterDirc(`insert into t3 values (2,2.1),(3,3)`)
  1163  
  1164  	var input []string
  1165  	var output []struct {
  1166  		ALLEGROALLEGROSQL string
  1167  		Causet            []string
  1168  		Res               []string
  1169  	}
  1170  	s.testData.GetTestCases(c, &input, &output)
  1171  	for i, tt := range input {
  1172  		s.testData.OnRecord(func() {
  1173  			output[i].ALLEGROALLEGROSQL = tt
  1174  			output[i].Causet = s.testData.ConvertEventsToStrings(tk.MustQuery("explain " + tt).Events())
  1175  			output[i].Res = s.testData.ConvertEventsToStrings(tk.MustQuery(tt).Sort().Events())
  1176  		})
  1177  		tk.MustQuery("explain " + tt).Check(testkit.Events(output[i].Causet...))
  1178  		tk.MustQuery(tt).Sort().Check(testkit.Events(output[i].Res...))
  1179  	}
  1180  }
  1181  
  1182  func (s *testSuiteP2) TestUnion(c *C) {
  1183  	tk := testkit.NewTestKit(c, s.causetstore)
  1184  	tk.MustInterDirc("use test")
  1185  
  1186  	testALLEGROSQL := `drop causet if exists union_test; create causet union_test(id int);`
  1187  	tk.MustInterDirc(testALLEGROSQL)
  1188  
  1189  	testALLEGROSQL = `drop causet if exists union_test;`
  1190  	tk.MustInterDirc(testALLEGROSQL)
  1191  	testALLEGROSQL = `create causet union_test(id int);`
  1192  	tk.MustInterDirc(testALLEGROSQL)
  1193  	testALLEGROSQL = `insert union_test values (1),(2)`
  1194  	tk.MustInterDirc(testALLEGROSQL)
  1195  
  1196  	testALLEGROSQL = `select * from (select id from union_test union select id from union_test) t order by id;`
  1197  	r := tk.MustQuery(testALLEGROSQL)
  1198  	r.Check(testkit.Events("1", "2"))
  1199  
  1200  	r = tk.MustQuery("select 1 union all select 1")
  1201  	r.Check(testkit.Events("1", "1"))
  1202  
  1203  	r = tk.MustQuery("select 1 union all select 1 union select 1")
  1204  	r.Check(testkit.Events("1"))
  1205  
  1206  	r = tk.MustQuery("select 1 as a union (select 2) order by a limit 1")
  1207  	r.Check(testkit.Events("1"))
  1208  
  1209  	r = tk.MustQuery("select 1 as a union (select 2) order by a limit 1, 1")
  1210  	r.Check(testkit.Events("2"))
  1211  
  1212  	r = tk.MustQuery("select id from union_test union all (select 1) order by id desc")
  1213  	r.Check(testkit.Events("2", "1", "1"))
  1214  
  1215  	r = tk.MustQuery("select id as a from union_test union (select 1) order by a desc")
  1216  	r.Check(testkit.Events("2", "1"))
  1217  
  1218  	r = tk.MustQuery(`select null as a union (select "abc") order by a`)
  1219  	r.Check(testkit.Events("<nil>", "abc"))
  1220  
  1221  	r = tk.MustQuery(`select "abc" as a union (select 1) order by a`)
  1222  	r.Check(testkit.Events("1", "abc"))
  1223  
  1224  	tk.MustInterDirc("drop causet if exists t1")
  1225  	tk.MustInterDirc("create causet t1 (c int, d int)")
  1226  	tk.MustInterDirc("insert t1 values (NULL, 1)")
  1227  	tk.MustInterDirc("insert t1 values (1, 1)")
  1228  	tk.MustInterDirc("insert t1 values (1, 2)")
  1229  	tk.MustInterDirc("drop causet if exists t2")
  1230  	tk.MustInterDirc("create causet t2 (c int, d int)")
  1231  	tk.MustInterDirc("insert t2 values (1, 3)")
  1232  	tk.MustInterDirc("insert t2 values (1, 1)")
  1233  	tk.MustInterDirc("drop causet if exists t3")
  1234  	tk.MustInterDirc("create causet t3 (c int, d int)")
  1235  	tk.MustInterDirc("insert t3 values (3, 2)")
  1236  	tk.MustInterDirc("insert t3 values (4, 3)")
  1237  	r = tk.MustQuery(`select sum(c1), c2 from (select c c1, d c2 from t1 union all select d c1, c c2 from t2 union all select c c1, d c2 from t3) x group by c2 order by c2`)
  1238  	r.Check(testkit.Events("5 1", "4 2", "4 3"))
  1239  
  1240  	tk.MustInterDirc("drop causet if exists t1, t2, t3")
  1241  	tk.MustInterDirc("create causet t1 (a int primary key)")
  1242  	tk.MustInterDirc("create causet t2 (a int primary key)")
  1243  	tk.MustInterDirc("create causet t3 (a int primary key)")
  1244  	tk.MustInterDirc("insert t1 values (7), (8)")
  1245  	tk.MustInterDirc("insert t2 values (1), (9)")
  1246  	tk.MustInterDirc("insert t3 values (2), (3)")
  1247  	r = tk.MustQuery("select * from t1 union all select * from t2 union all (select * from t3) order by a limit 2")
  1248  	r.Check(testkit.Events("1", "2"))
  1249  
  1250  	tk.MustInterDirc("drop causet if exists t1, t2")
  1251  	tk.MustInterDirc("create causet t1 (a int)")
  1252  	tk.MustInterDirc("create causet t2 (a int)")
  1253  	tk.MustInterDirc("insert t1 values (2), (1)")
  1254  	tk.MustInterDirc("insert t2 values (3), (4)")
  1255  	r = tk.MustQuery("select * from t1 union all (select * from t2) order by a limit 1")
  1256  	r.Check(testkit.Events("1"))
  1257  	r = tk.MustQuery("select (select * from t1 where a != t.a union all (select * from t2 where a != t.a) order by a limit 1) from t1 t")
  1258  	r.Check(testkit.Events("1", "2"))
  1259  
  1260  	tk.MustInterDirc("drop causet if exists t")
  1261  	tk.MustInterDirc("create causet t (id int unsigned primary key auto_increment, c1 int, c2 int, index c1_c2 (c1, c2))")
  1262  	tk.MustInterDirc("insert into t (c1, c2) values (1, 1)")
  1263  	tk.MustInterDirc("insert into t (c1, c2) values (1, 2)")
  1264  	tk.MustInterDirc("insert into t (c1, c2) values (2, 3)")
  1265  	r = tk.MustQuery("select * from (select * from t where t.c1 = 1 union select * from t where t.id = 1) s order by s.id")
  1266  	r.Check(testkit.Events("1 1 1", "2 1 2"))
  1267  
  1268  	tk.MustInterDirc("drop causet if exists t")
  1269  	tk.MustInterDirc("CREATE TABLE t (f1 DATE)")
  1270  	tk.MustInterDirc("INSERT INTO t VALUES ('1978-11-26')")
  1271  	r = tk.MustQuery("SELECT f1+0 FROM t UNION SELECT f1+0 FROM t")
  1272  	r.Check(testkit.Events("19781126"))
  1273  
  1274  	tk.MustInterDirc("drop causet if exists t")
  1275  	tk.MustInterDirc("CREATE TABLE t (a int, b int)")
  1276  	tk.MustInterDirc("INSERT INTO t VALUES ('1', '1')")
  1277  	r = tk.MustQuery("select b from (SELECT * FROM t UNION ALL SELECT a, b FROM t order by a) t")
  1278  	r.Check(testkit.Events("1", "1"))
  1279  
  1280  	tk.MustInterDirc("drop causet if exists t")
  1281  	tk.MustInterDirc("CREATE TABLE t (a DECIMAL(4,2))")
  1282  	tk.MustInterDirc("INSERT INTO t VALUE(12.34)")
  1283  	r = tk.MustQuery("SELECT 1 AS c UNION select a FROM t")
  1284  	r.Sort().Check(testkit.Events("1.00", "12.34"))
  1285  
  1286  	// #issue3771
  1287  	r = tk.MustQuery("SELECT 'a' UNION SELECT CONCAT('a', -4)")
  1288  	r.Sort().Check(testkit.Events("a", "a-4"))
  1289  
  1290  	// test race
  1291  	tk.MustQuery("SELECT @x:=0 UNION ALL SELECT @x:=0 UNION ALL SELECT @x")
  1292  
  1293  	// test field tp
  1294  	tk.MustInterDirc("drop causet if exists t1, t2")
  1295  	tk.MustInterDirc("CREATE TABLE t1 (a date)")
  1296  	tk.MustInterDirc("CREATE TABLE t2 (a date)")
  1297  	tk.MustInterDirc("SELECT a from t1 UNION select a FROM t2")
  1298  	tk.MustQuery("show create causet t1").Check(testkit.Events("t1 CREATE TABLE `t1` (\n" + "  `a` date DEFAULT NULL\n" + ") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin"))
  1299  
  1300  	// Move from stochastik test.
  1301  	tk.MustInterDirc("drop causet if exists t1, t2")
  1302  	tk.MustInterDirc("create causet t1 (c double);")
  1303  	tk.MustInterDirc("create causet t2 (c double);")
  1304  	tk.MustInterDirc("insert into t1 value (73);")
  1305  	tk.MustInterDirc("insert into t2 value (930);")
  1306  	// If set unspecified defCausumn flen to 0, it will cause bug in union.
  1307  	// This test is used to prevent the bug reappear.
  1308  	tk.MustQuery("select c from t1 union (select c from t2) order by c").Check(testkit.Events("73", "930"))
  1309  
  1310  	// issue 5703
  1311  	tk.MustInterDirc("drop causet if exists t")
  1312  	tk.MustInterDirc("create causet t(a date)")
  1313  	tk.MustInterDirc("insert into t value ('2020-01-01'), ('2020-01-02')")
  1314  	r = tk.MustQuery("(select a from t where a < 0) union (select a from t where a > 0) order by a")
  1315  	r.Check(testkit.Events("2020-01-01", "2020-01-02"))
  1316  
  1317  	tk.MustInterDirc("drop causet if exists t")
  1318  	tk.MustInterDirc("create causet t(a int)")
  1319  	tk.MustInterDirc("insert into t value(0),(0)")
  1320  	tk.MustQuery("select 1 from (select a from t union all select a from t) tmp").Check(testkit.Events("1", "1", "1", "1"))
  1321  	tk.MustQuery("select 10 as a from dual union select a from t order by a desc limit 1 ").Check(testkit.Events("10"))
  1322  	tk.MustQuery("select -10 as a from dual union select a from t order by a limit 1 ").Check(testkit.Events("-10"))
  1323  	tk.MustQuery("select count(1) from (select a from t union all select a from t) tmp").Check(testkit.Events("4"))
  1324  
  1325  	err := tk.InterDircToErr("select 1 from (select a from t limit 1 union all select a from t limit 1) tmp")
  1326  	c.Assert(err, NotNil)
  1327  	terr := errors.Cause(err).(*terror.Error)
  1328  	c.Assert(terr.Code(), Equals, errors.ErrCode(allegrosql.ErrWrongUsage))
  1329  
  1330  	err = tk.InterDircToErr("select 1 from (select a from t order by a union all select a from t limit 1) tmp")
  1331  	c.Assert(err, NotNil)
  1332  	terr = errors.Cause(err).(*terror.Error)
  1333  	c.Assert(terr.Code(), Equals, errors.ErrCode(allegrosql.ErrWrongUsage))
  1334  
  1335  	_, err = tk.InterDirc("(select a from t order by a) union all select a from t limit 1 union all select a from t limit 1")
  1336  	c.Assert(terror.ErrorEqual(err, causetembedded.ErrWrongUsage), IsTrue, Commentf("err %v", err))
  1337  
  1338  	_, err = tk.InterDirc("(select a from t limit 1) union all select a from t limit 1")
  1339  	c.Assert(err, IsNil)
  1340  	_, err = tk.InterDirc("(select a from t order by a) union all select a from t order by a")
  1341  	c.Assert(err, IsNil)
  1342  
  1343  	tk.MustInterDirc("drop causet if exists t")
  1344  	tk.MustInterDirc("create causet t(a int)")
  1345  	tk.MustInterDirc("insert into t value(1),(2),(3)")
  1346  
  1347  	tk.MustQuery("(select a from t order by a limit 2) union all (select a from t order by a desc limit 2) order by a desc limit 1,2").Check(testkit.Events("2", "2"))
  1348  	tk.MustQuery("select a from t union all select a from t order by a desc limit 5").Check(testkit.Events("3", "3", "2", "2", "1"))
  1349  	tk.MustQuery("(select a from t order by a desc limit 2) union all select a from t group by a order by a").Check(testkit.Rows("1", "2", "2", "3", "3"))
  1350  	tk.MustQuery("(select a from t order by a desc limit 2) union all select 33 as a order by a desc limit 2").Check(testkit.Rows("33", "3"))
  1351  
  1352  	tk.MustQuery("select 1 union select 1 union all select 1").Check(testkit.Rows("1", "1"))
  1353  	tk.MustQuery("select 1 union all select 1 union select 1").Check(testkit.Rows("1"))
  1354  
  1355  	tk.MustInterDirc("drop causet if exists t1, t2")
  1356  	tk.MustInterDirc(`create causet t1(a bigint, b bigint);`)
  1357  	tk.MustInterDirc(`create causet t2(a bigint, b bigint);`)
  1358  	tk.MustInterDirc(`insert into t1 values(1, 1);`)
  1359  	tk.MustInterDirc(`insert into t1 select * from t1;`)
  1360  	tk.MustInterDirc(`insert into t1 select * from t1;`)
  1361  	tk.MustInterDirc(`insert into t1 select * from t1;`)
  1362  	tk.MustInterDirc(`insert into t1 select * from t1;`)
  1363  	tk.MustInterDirc(`insert into t1 select * from t1;`)
  1364  	tk.MustInterDirc(`insert into t1 select * from t1;`)
  1365  	tk.MustInterDirc(`insert into t2 values(1, 1);`)
  1366  	tk.MustInterDirc(`set @@milevadb_init_chunk_size=2;`)
  1367  	tk.MustInterDirc(`set @@sql_mode="";`)
  1368  	tk.MustQuery(`select count(*) from (select t1.a, t1.b from t1 left join t2 on t1.a=t2.a union all select t1.a, t1.a from t1 left join t2 on t1.a=t2.a) tmp;`).Check(testkit.Rows("128"))
  1369  	tk.MustQuery(`select tmp.a, count(*) from (select t1.a, t1.b from t1 left join t2 on t1.a=t2.a union all select t1.a, t1.a from t1 left join t2 on t1.a=t2.a) tmp;`).Check(testkit.Rows("1 128"))
  1370  
  1371  	tk.MustInterDirc("drop causet if exists t")
  1372  	tk.MustInterDirc("create causet t(a int, b int)")
  1373  	tk.MustInterDirc("insert into t value(1 ,2)")
  1374  	tk.MustQuery("select a, b from (select a, 0 as d, b from t union all select a, 0 as d, b from t) test;").Check(testkit.Rows("1 2", "1 2"))
  1375  
  1376  	// #issue 8141
  1377  	tk.MustInterDirc("drop causet if exists t1")
  1378  	tk.MustInterDirc("create causet t1(a int, b int)")
  1379  	tk.MustInterDirc("insert into t1 value(1,2),(1,1),(2,2),(2,2),(3,2),(3,2)")
  1380  	tk.MustInterDirc("set @@milevadb_init_chunk_size=2;")
  1381  	tk.MustQuery("select count(*) from (select a as c, a as d from t1 union all select a, b from t1) t;").Check(testkit.Rows("12"))
  1382  
  1383  	// #issue 8189 and #issue 8199
  1384  	tk.MustInterDirc("drop causet if exists t1")
  1385  	tk.MustInterDirc("drop causet if exists t2")
  1386  	tk.MustInterDirc("CREATE TABLE t1 (a int not null, b char (10) not null)")
  1387  	tk.MustInterDirc("insert into t1 values(1,'a'),(2,'b'),(3,'c'),(3,'c')")
  1388  	tk.MustInterDirc("CREATE TABLE t2 (a int not null, b char (10) not null)")
  1389  	tk.MustInterDirc("insert into t2 values(1,'a'),(2,'b'),(3,'c'),(3,'c')")
  1390  	tk.MustQuery("select a from t1 union select a from t1 order by (select a+1);").Check(testkit.Rows("1", "2", "3"))
  1391  
  1392  	// #issue 8201
  1393  	for i := 0; i < 4; i++ {
  1394  		tk.MustQuery("SELECT(SELECT 0 AS a FROM dual UNION SELECT 1 AS a FROM dual ORDER BY a ASC  LIMIT 1) AS dev").Check(testkit.Rows("0"))
  1395  	}
  1396  
  1397  	// #issue 8231
  1398  	tk.MustInterDirc("drop causet if exists t1")
  1399  	tk.MustInterDirc("CREATE TABLE t1 (uid int(1))")
  1400  	tk.MustInterDirc("INSERT INTO t1 SELECT 150")
  1401  	tk.MustQuery("SELECT 'a' UNION SELECT uid FROM t1 order by 1 desc;").Check(testkit.Rows("a", "150"))
  1402  
  1403  	// #issue 8196
  1404  	tk.MustInterDirc("drop causet if exists t1")
  1405  	tk.MustInterDirc("drop causet if exists t2")
  1406  	tk.MustInterDirc("CREATE TABLE t1 (a int not null, b char (10) not null)")
  1407  	tk.MustInterDirc("insert into t1 values(1,'a'),(2,'b'),(3,'c'),(3,'c')")
  1408  	tk.MustInterDirc("CREATE TABLE t2 (a int not null, b char (10) not null)")
  1409  	tk.MustInterDirc("insert into t2 values(3,'c'),(4,'d'),(5,'f'),(6,'e')")
  1410  	tk.MustInterDirc("analyze causet t1")
  1411  	tk.MustInterDirc("analyze causet t2")
  1412  	_, err = tk.InterDirc("(select a,b from t1 limit 2) union all (select a,b from t2 order by a limit 1) order by t1.b")
  1413  	c.Assert(err.Error(), Equals, "[causet:1250]Block 't1' from one of the SELECTs cannot be used in global ORDER clause")
  1414  
  1415  	// #issue 9900
  1416  	tk.MustInterDirc("drop causet if exists t")
  1417  	tk.MustInterDirc("create causet t(a int, b decimal(6, 3))")
  1418  	tk.MustInterDirc("insert into t values(1, 1.000)")
  1419  	tk.MustQuery("select count(distinct a), sum(distinct a), avg(distinct a) from (select a from t union all select b from t) tmp;").Check(testkit.Rows("1 1.000 1.0000000"))
  1420  }
  1421  
  1422  func (s *testSuite2) TestUnionLimit(c *C) {
  1423  	tk := testkit.NewTestKit(c, s.causetstore)
  1424  	tk.MustInterDirc("use test")
  1425  	tk.MustInterDirc("drop causet if exists union_limit")
  1426  	tk.MustInterDirc("create causet union_limit (id int) partition by hash(id) partitions 30")
  1427  	for i := 0; i < 60; i++ {
  1428  		tk.MustInterDirc(fmt.Sprintf("insert into union_limit values (%d)", i))
  1429  	}
  1430  	// Cover the code for worker count limit in the union interlock.
  1431  	tk.MustQuery("select * from union_limit limit 10")
  1432  }
  1433  
  1434  func (s *testSuiteP1) TestNeighbouringProj(c *C) {
  1435  	tk := testkit.NewTestKit(c, s.causetstore)
  1436  	tk.MustInterDirc("use test")
  1437  
  1438  	tk.MustInterDirc("drop causet if exists t1, t2")
  1439  	tk.MustInterDirc("create causet t1(a int, b int)")
  1440  	tk.MustInterDirc("create causet t2(a int, b int)")
  1441  	tk.MustInterDirc("insert into t1 value(1, 1), (2, 2)")
  1442  	tk.MustInterDirc("insert into t2 value(1, 1), (2, 2)")
  1443  	tk.MustQuery("select sum(c) from (select t1.a as a, t1.a as c, length(t1.b) from t1  union select a, b, b from t2) t;").Check(testkit.Rows("5"))
  1444  
  1445  	tk.MustInterDirc("drop causet if exists t")
  1446  	tk.MustInterDirc("create causet t(a bigint, b bigint, c bigint);")
  1447  	tk.MustInterDirc("insert into t values(1, 1, 1), (2, 2, 2), (3, 3, 3);")
  1448  	rs := tk.MustQuery("select cast(count(a) as signed), a as another, a from t group by a order by cast(count(a) as signed), a limit 10;")
  1449  	rs.Check(testkit.Rows("1 1 1", "1 2 2", "1 3 3"))
  1450  }
  1451  
  1452  func (s *testSuiteP1) TestIn(c *C) {
  1453  	tk := testkit.NewTestKit(c, s.causetstore)
  1454  	tk.MustInterDirc("use test")
  1455  	tk.MustInterDirc(`drop causet if exists t`)
  1456  	tk.MustInterDirc(`create causet t (c1 int primary key, c2 int, key c (c2));`)
  1457  	for i := 0; i <= 200; i++ {
  1458  		tk.MustInterDirc(fmt.Sprintf("insert t values(%d, %d)", i, i))
  1459  	}
  1460  	queryStr := `select c2 from t where c1 in ('7', '10', '112', '111', '98', '106', '100', '9', '18', '17') order by c2`
  1461  	r := tk.MustQuery(queryStr)
  1462  	r.Check(testkit.Rows("7", "9", "10", "17", "18", "98", "100", "106", "111", "112"))
  1463  
  1464  	queryStr = `select c2 from t where c1 in ('7a')`
  1465  	tk.MustQuery(queryStr).Check(testkit.Rows("7"))
  1466  }
  1467  
  1468  func (s *testSuiteP1) TestBlockPKisHandleScan(c *C) {
  1469  	tk := testkit.NewTestKit(c, s.causetstore)
  1470  	tk.MustInterDirc("use test")
  1471  	tk.MustInterDirc("drop causet if exists t")
  1472  	tk.MustInterDirc("create causet t (a int PRIMARY KEY AUTO_INCREMENT)")
  1473  	tk.MustInterDirc("insert t values (),()")
  1474  	tk.MustInterDirc("insert t values (-100),(0)")
  1475  
  1476  	tests := []struct {
  1477  		allegrosql string
  1478  		result     [][]interface{}
  1479  	}{
  1480  		{
  1481  			"select * from t",
  1482  			testkit.Rows("-100", "1", "2", "3"),
  1483  		},
  1484  		{
  1485  			"select * from t where a = 1",
  1486  			testkit.Rows("1"),
  1487  		},
  1488  		{
  1489  			"select * from t where a != 1",
  1490  			testkit.Rows("-100", "2", "3"),
  1491  		},
  1492  		{
  1493  			"select * from t where a >= '1.1'",
  1494  			testkit.Rows("2", "3"),
  1495  		},
  1496  		{
  1497  			"select * from t where a < '1.1'",
  1498  			testkit.Rows("-100", "1"),
  1499  		},
  1500  		{
  1501  			"select * from t where a > '-100.1' and a < 2",
  1502  			testkit.Rows("-100", "1"),
  1503  		},
  1504  		{
  1505  			"select * from t where a is null",
  1506  			testkit.Rows(),
  1507  		}, {
  1508  			"select * from t where a is true",
  1509  			testkit.Rows("-100", "1", "2", "3"),
  1510  		}, {
  1511  			"select * from t where a is false",
  1512  			testkit.Rows(),
  1513  		},
  1514  		{
  1515  			"select * from t where a in (1, 2)",
  1516  			testkit.Rows("1", "2"),
  1517  		},
  1518  		{
  1519  			"select * from t where a between 1 and 2",
  1520  			testkit.Rows("1", "2"),
  1521  		},
  1522  	}
  1523  
  1524  	for _, tt := range tests {
  1525  		result := tk.MustQuery(tt.allegrosql)
  1526  		result.Check(tt.result)
  1527  	}
  1528  }
  1529  
  1530  func (s *testSuite8) TestIndexScan(c *C) {
  1531  	tk := testkit.NewTestKit(c, s.causetstore)
  1532  	tk.MustInterDirc("use test")
  1533  	tk.MustInterDirc("drop causet if exists t")
  1534  	tk.MustInterDirc("create causet t (a int unique)")
  1535  	tk.MustInterDirc("insert t values (-1), (2), (3), (5), (6), (7), (8), (9)")
  1536  	result := tk.MustQuery("select a from t where a < 0 or (a >= 2.1 and a < 5.1) or ( a > 5.9 and a <= 7.9) or a > '8.1'")
  1537  	result.Check(testkit.Rows("-1", "3", "5", "6", "7", "9"))
  1538  	tk.MustInterDirc("drop causet if exists t")
  1539  	tk.MustInterDirc("create causet t (a int unique)")
  1540  	tk.MustInterDirc("insert t values (0)")
  1541  	result = tk.MustQuery("select NULL from t ")
  1542  	result.Check(testkit.Rows("<nil>"))
  1543  	// test for double read
  1544  	tk.MustInterDirc("drop causet if exists t")
  1545  	tk.MustInterDirc("create causet t (a int unique, b int)")
  1546  	tk.MustInterDirc("insert t values (5, 0)")
  1547  	tk.MustInterDirc("insert t values (4, 0)")
  1548  	tk.MustInterDirc("insert t values (3, 0)")
  1549  	tk.MustInterDirc("insert t values (2, 0)")
  1550  	tk.MustInterDirc("insert t values (1, 0)")
  1551  	tk.MustInterDirc("insert t values (0, 0)")
  1552  	result = tk.MustQuery("select * from t order by a limit 3")
  1553  	result.Check(testkit.Rows("0 0", "1 0", "2 0"))
  1554  	tk.MustInterDirc("drop causet if exists t")
  1555  	tk.MustInterDirc("create causet t (a int unique, b int)")
  1556  	tk.MustInterDirc("insert t values (0, 1)")
  1557  	tk.MustInterDirc("insert t values (1, 2)")
  1558  	tk.MustInterDirc("insert t values (2, 1)")
  1559  	tk.MustInterDirc("insert t values (3, 2)")
  1560  	tk.MustInterDirc("insert t values (4, 1)")
  1561  	tk.MustInterDirc("insert t values (5, 2)")
  1562  	result = tk.MustQuery("select * from t where a < 5 and b = 1 limit 2")
  1563  	result.Check(testkit.Rows("0 1", "2 1"))
  1564  	tk.MustInterDirc("drop causet if exists tab1")
  1565  	tk.MustInterDirc("CREATE TABLE tab1(pk INTEGER PRIMARY KEY, defCaus0 INTEGER, defCaus1 FLOAT, defCaus3 INTEGER, defCaus4 FLOAT)")
  1566  	tk.MustInterDirc("CREATE INDEX idx_tab1_0 on tab1 (defCaus0)")
  1567  	tk.MustInterDirc("CREATE INDEX idx_tab1_1 on tab1 (defCaus1)")
  1568  	tk.MustInterDirc("CREATE INDEX idx_tab1_3 on tab1 (defCaus3)")
  1569  	tk.MustInterDirc("CREATE INDEX idx_tab1_4 on tab1 (defCaus4)")
  1570  	tk.MustInterDirc("INSERT INTO tab1 VALUES(1,37,20.85,30,10.69)")
  1571  	result = tk.MustQuery("SELECT pk FROM tab1 WHERE ((defCaus3 <= 6 OR defCaus3 < 29 AND (defCaus0 < 41)) OR defCaus3 > 42) AND defCaus1 >= 96.1 AND defCaus3 = 30 AND defCaus3 > 17 AND (defCaus0 BETWEEN 36 AND 42)")
  1572  	result.Check(testkit.Rows())
  1573  	tk.MustInterDirc("drop causet if exists tab1")
  1574  	tk.MustInterDirc("CREATE TABLE tab1(pk INTEGER PRIMARY KEY, a INTEGER, b INTEGER)")
  1575  	tk.MustInterDirc("CREATE INDEX idx_tab1_0 on tab1 (a)")
  1576  	tk.MustInterDirc("INSERT INTO tab1 VALUES(1,1,1)")
  1577  	tk.MustInterDirc("INSERT INTO tab1 VALUES(2,2,1)")
  1578  	tk.MustInterDirc("INSERT INTO tab1 VALUES(3,1,2)")
  1579  	tk.MustInterDirc("INSERT INTO tab1 VALUES(4,2,2)")
  1580  	result = tk.MustQuery("SELECT * FROM tab1 WHERE pk <= 3 AND a = 1")
  1581  	result.Check(testkit.Rows("1 1 1", "3 1 2"))
  1582  	result = tk.MustQuery("SELECT * FROM tab1 WHERE pk <= 4 AND a = 1 AND b = 2")
  1583  	result.Check(testkit.Rows("3 1 2"))
  1584  	tk.MustInterDirc("CREATE INDEX idx_tab1_1 on tab1 (b, a)")
  1585  	result = tk.MustQuery("SELECT pk FROM tab1 WHERE b > 1")
  1586  	result.Check(testkit.Rows("3", "4"))
  1587  
  1588  	tk.MustInterDirc("drop causet if exists t")
  1589  	tk.MustInterDirc("CREATE TABLE t (a varchar(3), index(a))")
  1590  	tk.MustInterDirc("insert t values('aaa'), ('aab')")
  1591  	result = tk.MustQuery("select * from t where a >= 'aaaa' and a < 'aabb'")
  1592  	result.Check(testkit.Rows("aab"))
  1593  
  1594  	tk.MustInterDirc("drop causet if exists t")
  1595  	tk.MustInterDirc("CREATE TABLE t (a int primary key, b int, c int, index(c))")
  1596  	tk.MustInterDirc("insert t values(1, 1, 1), (2, 2, 2), (4, 4, 4), (3, 3, 3), (5, 5, 5)")
  1597  	// Test for double read and top n.
  1598  	result = tk.MustQuery("select a from t where c >= 2 order by b desc limit 1")
  1599  	result.Check(testkit.Rows("5"))
  1600  
  1601  	tk.MustInterDirc("drop causet if exists t")
  1602  	tk.MustInterDirc("create causet t(a varchar(50) primary key, b int, c int, index idx(b))")
  1603  	tk.MustInterDirc("insert into t values('aa', 1, 1)")
  1604  	tk.MustQuery("select * from t use index(idx) where a > 'a'").Check(testkit.Rows("aa 1 1"))
  1605  
  1606  	// fix issue9636
  1607  	tk.MustInterDirc("drop causet if exists t")
  1608  	tk.MustInterDirc("CREATE TABLE `t` (a int, KEY (a))")
  1609  	result = tk.MustQuery(`SELECT * FROM (SELECT * FROM (SELECT a as d FROM t WHERE a IN ('100')) AS x WHERE x.d < "123" ) tmp_count`)
  1610  	result.Check(testkit.Rows())
  1611  }
  1612  
  1613  func (s *testSuiteP1) TestIndexReverseOrder(c *C) {
  1614  	tk := testkit.NewTestKit(c, s.causetstore)
  1615  	tk.MustInterDirc("use test")
  1616  	tk.MustInterDirc("drop causet if exists t")
  1617  	tk.MustInterDirc("create causet t (a int primary key auto_increment, b int, index idx (b))")
  1618  	tk.MustInterDirc("insert t (b) values (0), (1), (2), (3), (4), (5), (6), (7), (8), (9)")
  1619  	result := tk.MustQuery("select b from t order by b desc")
  1620  	result.Check(testkit.Rows("9", "8", "7", "6", "5", "4", "3", "2", "1", "0"))
  1621  	result = tk.MustQuery("select b from t where b <3 or (b >=6 and b < 8) order by b desc")
  1622  	result.Check(testkit.Rows("7", "6", "2", "1", "0"))
  1623  
  1624  	tk.MustInterDirc("drop causet if exists t")
  1625  	tk.MustInterDirc("create causet t (a int, b int, index idx (b, a))")
  1626  	tk.MustInterDirc("insert t values (0, 2), (1, 2), (2, 2), (0, 1), (1, 1), (2, 1), (0, 0), (1, 0), (2, 0)")
  1627  	result = tk.MustQuery("select b, a from t order by b, a desc")
  1628  	result.Check(testkit.Rows("0 2", "0 1", "0 0", "1 2", "1 1", "1 0", "2 2", "2 1", "2 0"))
  1629  }
  1630  
  1631  func (s *testSuiteP1) TestBlockReverseOrder(c *C) {
  1632  	tk := testkit.NewTestKit(c, s.causetstore)
  1633  	tk.MustInterDirc("use test")
  1634  	tk.MustInterDirc("drop causet if exists t")
  1635  	tk.MustInterDirc("create causet t (a int primary key auto_increment, b int)")
  1636  	tk.MustInterDirc("insert t (b) values (1), (2), (3), (4), (5), (6), (7), (8), (9)")
  1637  	result := tk.MustQuery("select b from t order by a desc")
  1638  	result.Check(testkit.Rows("9", "8", "7", "6", "5", "4", "3", "2", "1"))
  1639  	result = tk.MustQuery("select a from t where a <3 or (a >=6 and a < 8) order by a desc")
  1640  	result.Check(testkit.Rows("7", "6", "2", "1"))
  1641  }
  1642  
  1643  func (s *testSuiteP1) TestDefaultNull(c *C) {
  1644  	tk := testkit.NewTestKit(c, s.causetstore)
  1645  	tk.MustInterDirc("use test")
  1646  	tk.MustInterDirc("drop causet if exists t")
  1647  	tk.MustInterDirc("create causet t (a int primary key auto_increment, b int default 1, c int)")
  1648  	tk.MustInterDirc("insert t values ()")
  1649  	tk.MustQuery("select * from t").Check(testkit.Rows("1 1 <nil>"))
  1650  	tk.MustInterDirc("uFIDelate t set b = NULL where a = 1")
  1651  	tk.MustQuery("select * from t").Check(testkit.Rows("1 <nil> <nil>"))
  1652  	tk.MustInterDirc("uFIDelate t set c = 1")
  1653  	tk.MustQuery("select * from t ").Check(testkit.Rows("1 <nil> 1"))
  1654  	tk.MustInterDirc("delete from t where a = 1")
  1655  	tk.MustInterDirc("insert t (a) values (1)")
  1656  	tk.MustQuery("select * from t").Check(testkit.Rows("1 1 <nil>"))
  1657  }
  1658  
  1659  func (s *testSuiteP1) TestUnsignedPKDeferredCauset(c *C) {
  1660  	tk := testkit.NewTestKit(c, s.causetstore)
  1661  	tk.MustInterDirc("use test")
  1662  	tk.MustInterDirc("drop causet if exists t")
  1663  	tk.MustInterDirc("create causet t (a int unsigned primary key, b int, c int, key idx_ba (b, c, a));")
  1664  	tk.MustInterDirc("insert t values (1, 1, 1)")
  1665  	result := tk.MustQuery("select * from t;")
  1666  	result.Check(testkit.Rows("1 1 1"))
  1667  	tk.MustInterDirc("uFIDelate t set c=2 where a=1;")
  1668  	result = tk.MustQuery("select * from t where b=1;")
  1669  	result.Check(testkit.Rows("1 1 2"))
  1670  }
  1671  
  1672  func (s *testSuiteP1) TestJSON(c *C) {
  1673  	tk := testkit.NewTestKit(c, s.causetstore)
  1674  
  1675  	tk.MustInterDirc("use test")
  1676  	tk.MustInterDirc("drop causet if exists test_json")
  1677  	tk.MustInterDirc("create causet test_json (id int, a json)")
  1678  	tk.MustInterDirc(`insert into test_json (id, a) values (1, '{"a":[1,"2",{"aa":"bb"},4],"b":true}')`)
  1679  	tk.MustInterDirc(`insert into test_json (id, a) values (2, "null")`)
  1680  	tk.MustInterDirc(`insert into test_json (id, a) values (3, null)`)
  1681  	tk.MustInterDirc(`insert into test_json (id, a) values (4, 'true')`)
  1682  	tk.MustInterDirc(`insert into test_json (id, a) values (5, '3')`)
  1683  	tk.MustInterDirc(`insert into test_json (id, a) values (5, '4.0')`)
  1684  	tk.MustInterDirc(`insert into test_json (id, a) values (6, '"string"')`)
  1685  
  1686  	result := tk.MustQuery(`select tj.a from test_json tj order by tj.id`)
  1687  	result.Check(testkit.Rows(`{"a": [1, "2", {"aa": "bb"}, 4], "b": true}`, "null", "<nil>", "true", "3", "4", `"string"`))
  1688  
  1689  	// Check json_type function
  1690  	result = tk.MustQuery(`select json_type(a) from test_json tj order by tj.id`)
  1691  	result.Check(testkit.Rows("OBJECT", "NULL", "<nil>", "BOOLEAN", "INTEGER", "DOUBLE", "STRING"))
  1692  
  1693  	// Check json compare with primitives.
  1694  	result = tk.MustQuery(`select a from test_json tj where a = 3`)
  1695  	result.Check(testkit.Rows("3"))
  1696  	result = tk.MustQuery(`select a from test_json tj where a = 4.0`)
  1697  	result.Check(testkit.Rows("4"))
  1698  	result = tk.MustQuery(`select a from test_json tj where a = true`)
  1699  	result.Check(testkit.Rows("true"))
  1700  	result = tk.MustQuery(`select a from test_json tj where a = "string"`)
  1701  	result.Check(testkit.Rows(`"string"`))
  1702  
  1703  	// Check cast(true/false as JSON).
  1704  	result = tk.MustQuery(`select cast(true as JSON)`)
  1705  	result.Check(testkit.Rows(`true`))
  1706  	result = tk.MustQuery(`select cast(false as JSON)`)
  1707  	result.Check(testkit.Rows(`false`))
  1708  
  1709  	// Check two json grammar sugar.
  1710  	result = tk.MustQuery(`select a->>'$.a[2].aa' as x, a->'$.b' as y from test_json having x is not null order by id`)
  1711  	result.Check(testkit.Rows(`bb true`))
  1712  	result = tk.MustQuery(`select a->'$.a[2].aa' as x, a->>'$.b' as y from test_json having x is not null order by id`)
  1713  	result.Check(testkit.Rows(`"bb" true`))
  1714  
  1715  	// Check some DBS limits for TEXT/BLOB/JSON defCausumn.
  1716  	var err error
  1717  	var terr *terror.Error
  1718  
  1719  	_, err = tk.InterDirc(`create causet test_bad_json(a json default '{}')`)
  1720  	c.Assert(err, NotNil)
  1721  	terr = errors.Cause(err).(*terror.Error)
  1722  	c.Assert(terr.Code(), Equals, errors.ErrCode(allegrosql.ErrBlobCantHaveDefault))
  1723  
  1724  	_, err = tk.InterDirc(`create causet test_bad_json(a blob default 'hello')`)
  1725  	c.Assert(err, NotNil)
  1726  	terr = errors.Cause(err).(*terror.Error)
  1727  	c.Assert(terr.Code(), Equals, errors.ErrCode(allegrosql.ErrBlobCantHaveDefault))
  1728  
  1729  	_, err = tk.InterDirc(`create causet test_bad_json(a text default 'world')`)
  1730  	c.Assert(err, NotNil)
  1731  	terr = errors.Cause(err).(*terror.Error)
  1732  	c.Assert(terr.Code(), Equals, errors.ErrCode(allegrosql.ErrBlobCantHaveDefault))
  1733  
  1734  	// check json fields cannot be used as key.
  1735  	_, err = tk.InterDirc(`create causet test_bad_json(id int, a json, key (a))`)
  1736  	c.Assert(err, NotNil)
  1737  	terr = errors.Cause(err).(*terror.Error)
  1738  	c.Assert(terr.Code(), Equals, errors.ErrCode(allegrosql.ErrJSONUsedAsKey))
  1739  
  1740  	// check CAST AS JSON.
  1741  	result = tk.MustQuery(`select CAST('3' AS JSON), CAST('{}' AS JSON), CAST(null AS JSON)`)
  1742  	result.Check(testkit.Rows(`3 {} <nil>`))
  1743  
  1744  	tk.MustQuery("select a, count(1) from test_json group by a order by a").Check(testkit.Rows(
  1745  		"<nil> 1",
  1746  		"null 1",
  1747  		"3 1",
  1748  		"4 1",
  1749  		`"string" 1`,
  1750  		"{\"a\": [1, \"2\", {\"aa\": \"bb\"}, 4], \"b\": true} 1",
  1751  		"true 1"))
  1752  
  1753  	// Check cast json to decimal.
  1754  	// NOTE: this test case contains a bug, it should be uncommented after the bug is fixed.
  1755  	// TODO: Fix bug https://github.com/whtcorpsinc/milevadb/issues/12178
  1756  	//tk.MustInterDirc("drop causet if exists test_json")
  1757  	//tk.MustInterDirc("create causet test_json ( a decimal(60,2) as (JSON_EXTRACT(b,'$.c')), b json );")
  1758  	//tk.MustInterDirc(`insert into test_json (b) values
  1759  	//	('{"c": "1267.1"}'),
  1760  	//	('{"c": "1267.01"}'),
  1761  	//	('{"c": "1267.1234"}'),
  1762  	//	('{"c": "1267.3456"}'),
  1763  	//	('{"c": "1234567890123456789012345678901234567890123456789012345"}'),
  1764  	//	('{"c": "1234567890123456789012345678901234567890123456789012345.12345"}');`)
  1765  	//
  1766  	//tk.MustQuery("select a from test_json;").Check(testkit.Rows("1267.10", "1267.01", "1267.12",
  1767  	//	"1267.35", "1234567890123456789012345678901234567890123456789012345.00",
  1768  	//	"1234567890123456789012345678901234567890123456789012345.12"))
  1769  }
  1770  
  1771  func (s *testSuiteP1) TestMultiUFIDelate(c *C) {
  1772  	tk := testkit.NewTestKit(c, s.causetstore)
  1773  	tk.MustInterDirc("use test")
  1774  	tk.MustInterDirc(`CREATE TABLE test_mu (a int primary key, b int, c int)`)
  1775  	tk.MustInterDirc(`INSERT INTO test_mu VALUES (1, 2, 3), (4, 5, 6), (7, 8, 9)`)
  1776  
  1777  	// Test INSERT ... ON DUPLICATE UFIDelATE set_lists.
  1778  	tk.MustInterDirc(`INSERT INTO test_mu VALUES (1, 2, 3) ON DUPLICATE KEY UFIDelATE b = 3, c = b`)
  1779  	result := tk.MustQuery(`SELECT * FROM test_mu ORDER BY a`)
  1780  	result.Check(testkit.Rows(`1 3 3`, `4 5 6`, `7 8 9`))
  1781  
  1782  	tk.MustInterDirc(`INSERT INTO test_mu VALUES (1, 2, 3) ON DUPLICATE KEY UFIDelATE c = 2, b = c+5`)
  1783  	result = tk.MustQuery(`SELECT * FROM test_mu ORDER BY a`)
  1784  	result.Check(testkit.Rows(`1 7 2`, `4 5 6`, `7 8 9`))
  1785  
  1786  	// Test UFIDelATE ... set_lists.
  1787  	tk.MustInterDirc(`UFIDelATE test_mu SET b = 0, c = b WHERE a = 4`)
  1788  	result = tk.MustQuery(`SELECT * FROM test_mu ORDER BY a`)
  1789  	result.Check(testkit.Rows(`1 7 2`, `4 0 0`, `7 8 9`))
  1790  
  1791  	tk.MustInterDirc(`UFIDelATE test_mu SET c = 8, b = c WHERE a = 4`)
  1792  	result = tk.MustQuery(`SELECT * FROM test_mu ORDER BY a`)
  1793  	result.Check(testkit.Rows(`1 7 2`, `4 8 8`, `7 8 9`))
  1794  
  1795  	tk.MustInterDirc(`UFIDelATE test_mu SET c = b, b = c WHERE a = 7`)
  1796  	result = tk.MustQuery(`SELECT * FROM test_mu ORDER BY a`)
  1797  	result.Check(testkit.Rows(`1 7 2`, `4 8 8`, `7 8 8`))
  1798  }
  1799  
  1800  func (s *testSuiteP1) TestGeneratedDeferredCausetWrite(c *C) {
  1801  	tk := testkit.NewTestKit(c, s.causetstore)
  1802  	tk.MustInterDirc("use test")
  1803  	_, err := tk.InterDirc(`CREATE TABLE test_gc_write (a int primary key auto_increment, b int, c int as (a+8) virtual)`)
  1804  	c.Assert(err.Error(), Equals, dbs.ErrGeneratedDeferredCausetRefAutoInc.GenWithStackByArgs("c").Error())
  1805  	tk.MustInterDirc(`CREATE TABLE test_gc_write (a int primary key auto_increment, b int, c int as (b+8) virtual)`)
  1806  	tk.MustInterDirc(`CREATE TABLE test_gc_write_1 (a int primary key, b int, c int)`)
  1807  
  1808  	tests := []struct {
  1809  		stmt string
  1810  		err  int
  1811  	}{
  1812  		// Can't modify generated defCausumn by values.
  1813  		{`insert into test_gc_write (a, b, c) values (1, 1, 1)`, allegrosql.ErrBadGeneratedDeferredCauset},
  1814  		{`insert into test_gc_write values (1, 1, 1)`, allegrosql.ErrBadGeneratedDeferredCauset},
  1815  		// Can't modify generated defCausumn by select clause.
  1816  		{`insert into test_gc_write select 1, 1, 1`, allegrosql.ErrBadGeneratedDeferredCauset},
  1817  		// Can't modify generated defCausumn by on duplicate clause.
  1818  		{`insert into test_gc_write (a, b) values (1, 1) on duplicate key uFIDelate c = 1`, allegrosql.ErrBadGeneratedDeferredCauset},
  1819  		// Can't modify generated defCausumn by set.
  1820  		{`insert into test_gc_write set a = 1, b = 1, c = 1`, allegrosql.ErrBadGeneratedDeferredCauset},
  1821  		// Can't modify generated defCausumn by uFIDelate clause.
  1822  		{`uFIDelate test_gc_write set c = 1`, allegrosql.ErrBadGeneratedDeferredCauset},
  1823  		// Can't modify generated defCausumn by multi-causet uFIDelate clause.
  1824  		{`uFIDelate test_gc_write, test_gc_write_1 set test_gc_write.c = 1`, allegrosql.ErrBadGeneratedDeferredCauset},
  1825  
  1826  		// Can insert without generated defCausumns.
  1827  		{`insert into test_gc_write (a, b) values (1, 1)`, 0},
  1828  		{`insert into test_gc_write set a = 2, b = 2`, 0},
  1829  		{`insert into test_gc_write (b) select c from test_gc_write`, 0},
  1830  		// Can uFIDelate without generated defCausumns.
  1831  		{`uFIDelate test_gc_write set b = 2 where a = 2`, 0},
  1832  		{`uFIDelate test_gc_write t1, test_gc_write_1 t2 set t1.b = 3, t2.b = 4`, 0},
  1833  
  1834  		// But now we can't do this, just as same with MyALLEGROSQL 5.7:
  1835  		{`insert into test_gc_write values (1, 1)`, allegrosql.ErrWrongValueCountOnRow},
  1836  		{`insert into test_gc_write select 1, 1`, allegrosql.ErrWrongValueCountOnRow},
  1837  		{`insert into test_gc_write (c) select a, b from test_gc_write`, allegrosql.ErrWrongValueCountOnRow},
  1838  		{`insert into test_gc_write (b, c) select a, b from test_gc_write`, allegrosql.ErrBadGeneratedDeferredCauset},
  1839  	}
  1840  	for _, tt := range tests {
  1841  		_, err := tk.InterDirc(tt.stmt)
  1842  		if tt.err != 0 {
  1843  			c.Assert(err, NotNil, Commentf("allegrosql is `%v`", tt.stmt))
  1844  			terr := errors.Cause(err).(*terror.Error)
  1845  			c.Assert(terr.Code(), Equals, errors.ErrCode(tt.err), Commentf("allegrosql is %v", tt.stmt))
  1846  		} else {
  1847  			c.Assert(err, IsNil)
  1848  		}
  1849  	}
  1850  }
  1851  
  1852  // TestGeneratedDeferredCausetRead tests select generated defCausumns from causet.
  1853  // They should be calculated from their generation memexs.
  1854  func (s *testSuiteP1) TestGeneratedDeferredCausetRead(c *C) {
  1855  	tk := testkit.NewTestKit(c, s.causetstore)
  1856  	tk.MustInterDirc("use test")
  1857  	tk.MustInterDirc(`CREATE TABLE test_gc_read(a int primary key, b int, c int as (a+b), d int as (a*b) stored, e int as (c*2))`)
  1858  
  1859  	result := tk.MustQuery(`SELECT generation_memex FROM information_schema.defCausumns WHERE block_name = 'test_gc_read' AND defCausumn_name = 'd'`)
  1860  	result.Check(testkit.Rows("`a` * `b`"))
  1861  
  1862  	// Insert only defCausumn a and b, leave c and d be calculated from them.
  1863  	tk.MustInterDirc(`INSERT INTO test_gc_read (a, b) VALUES (0,null),(1,2),(3,4)`)
  1864  	result = tk.MustQuery(`SELECT * FROM test_gc_read ORDER BY a`)
  1865  	result.Check(testkit.Rows(`0 <nil> <nil> <nil> <nil>`, `1 2 3 2 6`, `3 4 7 12 14`))
  1866  
  1867  	tk.MustInterDirc(`INSERT INTO test_gc_read SET a = 5, b = 10`)
  1868  	result = tk.MustQuery(`SELECT * FROM test_gc_read ORDER BY a`)
  1869  	result.Check(testkit.Rows(`0 <nil> <nil> <nil> <nil>`, `1 2 3 2 6`, `3 4 7 12 14`, `5 10 15 50 30`))
  1870  
  1871  	tk.MustInterDirc(`REPLACE INTO test_gc_read (a, b) VALUES (5, 6)`)
  1872  	result = tk.MustQuery(`SELECT * FROM test_gc_read ORDER BY a`)
  1873  	result.Check(testkit.Rows(`0 <nil> <nil> <nil> <nil>`, `1 2 3 2 6`, `3 4 7 12 14`, `5 6 11 30 22`))
  1874  
  1875  	tk.MustInterDirc(`INSERT INTO test_gc_read (a, b) VALUES (5, 8) ON DUPLICATE KEY UFIDelATE b = 9`)
  1876  	result = tk.MustQuery(`SELECT * FROM test_gc_read ORDER BY a`)
  1877  	result.Check(testkit.Rows(`0 <nil> <nil> <nil> <nil>`, `1 2 3 2 6`, `3 4 7 12 14`, `5 9 14 45 28`))
  1878  
  1879  	// Test select only-generated-defCausumn-without-dependences.
  1880  	result = tk.MustQuery(`SELECT c, d FROM test_gc_read`)
  1881  	result.Check(testkit.Rows(`<nil> <nil>`, `3 2`, `7 12`, `14 45`))
  1882  
  1883  	// Test select only virtual generated defCausumn that refers to other virtual generated defCausumns.
  1884  	result = tk.MustQuery(`SELECT e FROM test_gc_read`)
  1885  	result.Check(testkit.Rows(`<nil>`, `6`, `14`, `28`))
  1886  
  1887  	// Test order of on duplicate key uFIDelate list.
  1888  	tk.MustInterDirc(`INSERT INTO test_gc_read (a, b) VALUES (5, 8) ON DUPLICATE KEY UFIDelATE a = 6, b = a`)
  1889  	result = tk.MustQuery(`SELECT * FROM test_gc_read ORDER BY a`)
  1890  	result.Check(testkit.Rows(`0 <nil> <nil> <nil> <nil>`, `1 2 3 2 6`, `3 4 7 12 14`, `6 6 12 36 24`))
  1891  
  1892  	tk.MustInterDirc(`INSERT INTO test_gc_read (a, b) VALUES (6, 8) ON DUPLICATE KEY UFIDelATE b = 8, a = b`)
  1893  	result = tk.MustQuery(`SELECT * FROM test_gc_read ORDER BY a`)
  1894  	result.Check(testkit.Rows(`0 <nil> <nil> <nil> <nil>`, `1 2 3 2 6`, `3 4 7 12 14`, `8 8 16 64 32`))
  1895  
  1896  	// Test where-conditions on virtual/stored generated defCausumns.
  1897  	result = tk.MustQuery(`SELECT * FROM test_gc_read WHERE c = 7`)
  1898  	result.Check(testkit.Rows(`3 4 7 12 14`))
  1899  
  1900  	result = tk.MustQuery(`SELECT * FROM test_gc_read WHERE d = 64`)
  1901  	result.Check(testkit.Rows(`8 8 16 64 32`))
  1902  
  1903  	result = tk.MustQuery(`SELECT * FROM test_gc_read WHERE e = 6`)
  1904  	result.Check(testkit.Rows(`1 2 3 2 6`))
  1905  
  1906  	// Test uFIDelate where-conditions on virtual/generated defCausumns.
  1907  	tk.MustInterDirc(`UFIDelATE test_gc_read SET a = a + 100 WHERE c = 7`)
  1908  	result = tk.MustQuery(`SELECT * FROM test_gc_read WHERE c = 107`)
  1909  	result.Check(testkit.Rows(`103 4 107 412 214`))
  1910  
  1911  	// Test uFIDelate where-conditions on virtual/generated defCausumns.
  1912  	tk.MustInterDirc(`UFIDelATE test_gc_read m SET m.a = m.a + 100 WHERE c = 107`)
  1913  	result = tk.MustQuery(`SELECT * FROM test_gc_read WHERE c = 207`)
  1914  	result.Check(testkit.Rows(`203 4 207 812 414`))
  1915  
  1916  	tk.MustInterDirc(`UFIDelATE test_gc_read SET a = a - 200 WHERE d = 812`)
  1917  	result = tk.MustQuery(`SELECT * FROM test_gc_read WHERE d = 12`)
  1918  	result.Check(testkit.Rows(`3 4 7 12 14`))
  1919  
  1920  	tk.MustInterDirc(`INSERT INTO test_gc_read set a = 4, b = d + 1`)
  1921  	result = tk.MustQuery(`SELECT * FROM test_gc_read ORDER BY a`)
  1922  	result.Check(testkit.Rows(`0 <nil> <nil> <nil> <nil>`, `1 2 3 2 6`, `3 4 7 12 14`,
  1923  		`4 <nil> <nil> <nil> <nil>`, `8 8 16 64 32`))
  1924  	tk.MustInterDirc(`DELETE FROM test_gc_read where a = 4`)
  1925  
  1926  	// Test on-conditions on virtual/stored generated defCausumns.
  1927  	tk.MustInterDirc(`CREATE TABLE test_gc_help(a int primary key, b int, c int, d int, e int)`)
  1928  	tk.MustInterDirc(`INSERT INTO test_gc_help(a, b, c, d, e) SELECT * FROM test_gc_read`)
  1929  
  1930  	result = tk.MustQuery(`SELECT t1.* FROM test_gc_read t1 JOIN test_gc_help t2 ON t1.c = t2.c ORDER BY t1.a`)
  1931  	result.Check(testkit.Rows(`1 2 3 2 6`, `3 4 7 12 14`, `8 8 16 64 32`))
  1932  
  1933  	result = tk.MustQuery(`SELECT t1.* FROM test_gc_read t1 JOIN test_gc_help t2 ON t1.d = t2.d ORDER BY t1.a`)
  1934  	result.Check(testkit.Rows(`1 2 3 2 6`, `3 4 7 12 14`, `8 8 16 64 32`))
  1935  
  1936  	result = tk.MustQuery(`SELECT t1.* FROM test_gc_read t1 JOIN test_gc_help t2 ON t1.e = t2.e ORDER BY t1.a`)
  1937  	result.Check(testkit.Rows(`1 2 3 2 6`, `3 4 7 12 14`, `8 8 16 64 32`))
  1938  
  1939  	// Test generated defCausumn in subqueries.
  1940  	result = tk.MustQuery(`SELECT * FROM test_gc_read t WHERE t.a not in (SELECT t.a FROM test_gc_read t where t.c > 5)`)
  1941  	result.Sort().Check(testkit.Rows(`0 <nil> <nil> <nil> <nil>`, `1 2 3 2 6`))
  1942  
  1943  	result = tk.MustQuery(`SELECT * FROM test_gc_read t WHERE t.c in (SELECT t.c FROM test_gc_read t where t.c > 5)`)
  1944  	result.Sort().Check(testkit.Rows(`3 4 7 12 14`, `8 8 16 64 32`))
  1945  
  1946  	result = tk.MustQuery(`SELECT tt.b FROM test_gc_read tt WHERE tt.a = (SELECT max(t.a) FROM test_gc_read t WHERE t.c = tt.c) ORDER BY b`)
  1947  	result.Check(testkit.Rows(`2`, `4`, `8`))
  1948  
  1949  	// Test aggregation on virtual/stored generated defCausumns.
  1950  	result = tk.MustQuery(`SELECT c, sum(a) aa, max(d) dd, sum(e) ee FROM test_gc_read GROUP BY c ORDER BY aa`)
  1951  	result.Check(testkit.Rows(`<nil> 0 <nil> <nil>`, `3 1 2 6`, `7 3 12 14`, `16 8 64 32`))
  1952  
  1953  	result = tk.MustQuery(`SELECT a, sum(c), sum(d), sum(e) FROM test_gc_read GROUP BY a ORDER BY a`)
  1954  	result.Check(testkit.Rows(`0 <nil> <nil> <nil>`, `1 3 2 6`, `3 7 12 14`, `8 16 64 32`))
  1955  
  1956  	// Test multi-uFIDelate on generated defCausumns.
  1957  	tk.MustInterDirc(`UFIDelATE test_gc_read m, test_gc_read n SET m.a = m.a + 10, n.a = n.a + 10`)
  1958  	result = tk.MustQuery(`SELECT * FROM test_gc_read ORDER BY a`)
  1959  	result.Check(testkit.Rows(`10 <nil> <nil> <nil> <nil>`, `11 2 13 22 26`, `13 4 17 52 34`, `18 8 26 144 52`))
  1960  
  1961  	tk.MustInterDirc("drop causet if exists t")
  1962  	tk.MustInterDirc("create causet t(a int)")
  1963  	tk.MustInterDirc("insert into t values(18)")
  1964  	tk.MustInterDirc("uFIDelate test_gc_read set a = a+1 where a in (select a from t)")
  1965  	result = tk.MustQuery("select * from test_gc_read order by a")
  1966  	result.Check(testkit.Rows(`10 <nil> <nil> <nil> <nil>`, `11 2 13 22 26`, `13 4 17 52 34`, `19 8 27 152 54`))
  1967  
  1968  	// Test different types between generation memex and generated defCausumn.
  1969  	tk.MustInterDirc(`CREATE TABLE test_gc_read_cast(a VARCHAR(255), b VARCHAR(255), c INT AS (JSON_EXTRACT(a, b)), d INT AS (JSON_EXTRACT(a, b)) STORED)`)
  1970  	tk.MustInterDirc(`INSERT INTO test_gc_read_cast (a, b) VALUES ('{"a": "3"}', '$.a')`)
  1971  	result = tk.MustQuery(`SELECT c, d FROM test_gc_read_cast`)
  1972  	result.Check(testkit.Rows(`3 3`))
  1973  
  1974  	tk.MustInterDirc(`CREATE TABLE test_gc_read_cast_1(a VARCHAR(255), b VARCHAR(255), c ENUM("red", "yellow") AS (JSON_UNQUOTE(JSON_EXTRACT(a, b))))`)
  1975  	tk.MustInterDirc(`INSERT INTO test_gc_read_cast_1 (a, b) VALUES ('{"a": "yellow"}', '$.a')`)
  1976  	result = tk.MustQuery(`SELECT c FROM test_gc_read_cast_1`)
  1977  	result.Check(testkit.Rows(`yellow`))
  1978  
  1979  	tk.MustInterDirc(`CREATE TABLE test_gc_read_cast_2( a JSON, b JSON AS (a->>'$.a'))`)
  1980  	tk.MustInterDirc(`INSERT INTO test_gc_read_cast_2(a) VALUES ('{"a": "{    \\\"key\\\": \\\"\\u6d4b\\\"    }"}')`)
  1981  	result = tk.MustQuery(`SELECT b FROM test_gc_read_cast_2`)
  1982  	result.Check(testkit.Rows(`{"key": "测"}`))
  1983  
  1984  	tk.MustInterDirc(`CREATE TABLE test_gc_read_cast_3( a JSON, b JSON AS (a->>'$.a'), c INT AS (b * 3.14) )`)
  1985  	tk.MustInterDirc(`INSERT INTO test_gc_read_cast_3(a) VALUES ('{"a": "5"}')`)
  1986  	result = tk.MustQuery(`SELECT c FROM test_gc_read_cast_3`)
  1987  	result.Check(testkit.Rows(`16`))
  1988  
  1989  	_, err := tk.InterDirc(`INSERT INTO test_gc_read_cast_1 (a, b) VALUES ('{"a": "invalid"}', '$.a')`)
  1990  	c.Assert(err, NotNil)
  1991  
  1992  	// Test read generated defCausumns after drop some irrelevant defCausumn
  1993  	tk.MustInterDirc(`DROP TABLE IF EXISTS test_gc_read_m`)
  1994  	tk.MustInterDirc(`CREATE TABLE test_gc_read_m (a int primary key, b int, c int as (a+1), d int as (c*2))`)
  1995  	tk.MustInterDirc(`INSERT INTO test_gc_read_m(a) values (1), (2)`)
  1996  	tk.MustInterDirc(`ALTER TABLE test_gc_read_m DROP b`)
  1997  	result = tk.MustQuery(`SELECT * FROM test_gc_read_m`)
  1998  	result.Check(testkit.Rows(`1 2 4`, `2 3 6`))
  1999  
  2000  	// Test not null generated defCausumns.
  2001  	tk.MustInterDirc(`CREATE TABLE test_gc_read_1(a int primary key, b int, c int as (a+b) not null, d int as (a*b) stored)`)
  2002  	tk.MustInterDirc(`CREATE TABLE test_gc_read_2(a int primary key, b int, c int as (a+b), d int as (a*b) stored not null)`)
  2003  	tests := []struct {
  2004  		stmt string
  2005  		err  int
  2006  	}{
  2007  		// Can't insert these records, because generated defCausumns are not null.
  2008  		{`insert into test_gc_read_1(a, b) values (1, null)`, allegrosql.ErrBadNull},
  2009  		{`insert into test_gc_read_2(a, b) values (1, null)`, allegrosql.ErrBadNull},
  2010  	}
  2011  	for _, tt := range tests {
  2012  		_, err := tk.InterDirc(tt.stmt)
  2013  		if tt.err != 0 {
  2014  			c.Assert(err, NotNil)
  2015  			terr := errors.Cause(err).(*terror.Error)
  2016  			c.Assert(terr.Code(), Equals, errors.ErrCode(tt.err))
  2017  		} else {
  2018  			c.Assert(err, IsNil)
  2019  		}
  2020  	}
  2021  }
  2022  
  2023  // TestGeneratedDeferredCausetRead tests generated defCausumns using point get and batch point get
  2024  func (s *testSuiteP1) TestGeneratedDeferredCausetPointGet(c *C) {
  2025  	tk := testkit.NewTestKit(c, s.causetstore)
  2026  	tk.MustInterDirc("use test")
  2027  	tk.MustInterDirc("drop causet if exists tu")
  2028  	tk.MustInterDirc("CREATE TABLE tu(a int, b int, c int GENERATED ALWAYS AS (a + b) VIRTUAL, d int as (a * b) stored, " +
  2029  		"e int GENERATED ALWAYS as (b * 2) VIRTUAL, PRIMARY KEY (a), UNIQUE KEY ukc (c), unique key ukd(d), key ke(e))")
  2030  	tk.MustInterDirc("insert into tu(a, b) values(1, 2)")
  2031  	tk.MustInterDirc("insert into tu(a, b) values(5, 6)")
  2032  	tk.MustQuery("select * from tu for uFIDelate").Check(testkit.Rows("1 2 3 2 4", "5 6 11 30 12"))
  2033  	tk.MustQuery("select * from tu where a = 1").Check(testkit.Rows("1 2 3 2 4"))
  2034  	tk.MustQuery("select * from tu where a in (1, 2)").Check(testkit.Rows("1 2 3 2 4"))
  2035  	tk.MustQuery("select * from tu where c in (1, 2, 3)").Check(testkit.Rows("1 2 3 2 4"))
  2036  	tk.MustQuery("select * from tu where c = 3").Check(testkit.Rows("1 2 3 2 4"))
  2037  	tk.MustQuery("select d, e from tu where c = 3").Check(testkit.Rows("2 4"))
  2038  	tk.MustQuery("select * from tu where d in (1, 2, 3)").Check(testkit.Rows("1 2 3 2 4"))
  2039  	tk.MustQuery("select * from tu where d = 2").Check(testkit.Rows("1 2 3 2 4"))
  2040  	tk.MustQuery("select c, d from tu where d = 2").Check(testkit.Rows("3 2"))
  2041  	tk.MustQuery("select d, e from tu where e = 4").Check(testkit.Rows("2 4"))
  2042  	tk.MustQuery("select * from tu where e = 4").Check(testkit.Rows("1 2 3 2 4"))
  2043  	tk.MustInterDirc("uFIDelate tu set a = a + 1, b = b + 1 where c = 11")
  2044  	tk.MustQuery("select * from tu for uFIDelate").Check(testkit.Rows("1 2 3 2 4", "6 7 13 42 14"))
  2045  	tk.MustQuery("select * from tu where a = 6").Check(testkit.Rows("6 7 13 42 14"))
  2046  	tk.MustQuery("select * from tu where c in (5, 6, 13)").Check(testkit.Rows("6 7 13 42 14"))
  2047  	tk.MustQuery("select b, c, e, d from tu where c = 13").Check(testkit.Rows("7 13 14 42"))
  2048  	tk.MustQuery("select a, e, d from tu where c in (5, 6, 13)").Check(testkit.Rows("6 14 42"))
  2049  	tk.MustInterDirc("drop causet if exists tu")
  2050  }
  2051  
  2052  func (s *testSuiteP2) TestToPBExpr(c *C) {
  2053  	tk := testkit.NewTestKit(c, s.causetstore)
  2054  	tk.MustInterDirc("use test")
  2055  	tk.MustInterDirc("drop causet if exists t")
  2056  	tk.MustInterDirc("create causet t (a decimal(10,6), b decimal, index idx_b (b))")
  2057  	tk.MustInterDirc("set sql_mode = ''")
  2058  	tk.MustInterDirc("insert t values (1.1, 1.1)")
  2059  	tk.MustInterDirc("insert t values (2.4, 2.4)")
  2060  	tk.MustInterDirc("insert t values (3.3, 2.7)")
  2061  	result := tk.MustQuery("select * from t where a < 2.399999")
  2062  	result.Check(testkit.Rows("1.100000 1"))
  2063  	result = tk.MustQuery("select * from t where a > 1.5")
  2064  	result.Check(testkit.Rows("2.400000 2", "3.300000 3"))
  2065  	result = tk.MustQuery("select * from t where a <= 1.1")
  2066  	result.Check(testkit.Rows("1.100000 1"))
  2067  	result = tk.MustQuery("select * from t where b >= 3")
  2068  	result.Check(testkit.Rows("3.300000 3"))
  2069  	result = tk.MustQuery("select * from t where not (b = 1)")
  2070  	result.Check(testkit.Rows("2.400000 2", "3.300000 3"))
  2071  	result = tk.MustQuery("select * from t where b&1 = a|1")
  2072  	result.Check(testkit.Rows("1.100000 1"))
  2073  	result = tk.MustQuery("select * from t where b != 2 and b <=> 3")
  2074  	result.Check(testkit.Rows("3.300000 3"))
  2075  	result = tk.MustQuery("select * from t where b in (3)")
  2076  	result.Check(testkit.Rows("3.300000 3"))
  2077  	result = tk.MustQuery("select * from t where b not in (1, 2)")
  2078  	result.Check(testkit.Rows("3.300000 3"))
  2079  
  2080  	tk.MustInterDirc("drop causet if exists t")
  2081  	tk.MustInterDirc("create causet t (a varchar(255), b int)")
  2082  	tk.MustInterDirc("insert t values ('abc123', 1)")
  2083  	tk.MustInterDirc("insert t values ('ab123', 2)")
  2084  	result = tk.MustQuery("select * from t where a like 'ab%'")
  2085  	result.Check(testkit.Rows("abc123 1", "ab123 2"))
  2086  	result = tk.MustQuery("select * from t where a like 'ab_12'")
  2087  	result.Check(nil)
  2088  	tk.MustInterDirc("drop causet if exists t")
  2089  	tk.MustInterDirc("create causet t (a int primary key)")
  2090  	tk.MustInterDirc("insert t values (1)")
  2091  	tk.MustInterDirc("insert t values (2)")
  2092  	result = tk.MustQuery("select * from t where not (a = 1)")
  2093  	result.Check(testkit.Rows("2"))
  2094  	result = tk.MustQuery("select * from t where not(not (a = 1))")
  2095  	result.Check(testkit.Rows("1"))
  2096  	result = tk.MustQuery("select * from t where not(a != 1 and a != 2)")
  2097  	result.Check(testkit.Rows("1", "2"))
  2098  }
  2099  
  2100  func (s *testSuiteP2) TestCausetXAPI(c *C) {
  2101  	tk := testkit.NewTestKit(c, s.causetstore)
  2102  	tk.MustInterDirc("use test")
  2103  	tk.MustInterDirc("drop causet if exists t")
  2104  	tk.MustInterDirc("create causet t (a decimal(10,6), b decimal, index idx_b (b))")
  2105  	tk.MustInterDirc("set sql_mode = ''")
  2106  	tk.MustInterDirc("insert t values (1.1, 1.1)")
  2107  	tk.MustInterDirc("insert t values (2.2, 2.2)")
  2108  	tk.MustInterDirc("insert t values (3.3, 2.7)")
  2109  	result := tk.MustQuery("select * from t where a > 1.5")
  2110  	result.Check(testkit.Rows("2.200000 2", "3.300000 3"))
  2111  	result = tk.MustQuery("select * from t where b > 1.5")
  2112  	result.Check(testkit.Rows("2.200000 2", "3.300000 3"))
  2113  
  2114  	tk.MustInterDirc("drop causet if exists t")
  2115  	tk.MustInterDirc("create causet t (a time(3), b time, index idx_a (a))")
  2116  	tk.MustInterDirc("insert t values ('11:11:11', '11:11:11')")
  2117  	tk.MustInterDirc("insert t values ('11:11:12', '11:11:12')")
  2118  	tk.MustInterDirc("insert t values ('11:11:13', '11:11:13')")
  2119  	result = tk.MustQuery("select * from t where a > '11:11:11.5'")
  2120  	result.Check(testkit.Rows("11:11:12.000 11:11:12", "11:11:13.000 11:11:13"))
  2121  	result = tk.MustQuery("select * from t where b > '11:11:11.5'")
  2122  	result.Check(testkit.Rows("11:11:12.000 11:11:12", "11:11:13.000 11:11:13"))
  2123  }
  2124  
  2125  func (s *testSuiteP2) TestALLEGROSQLMode(c *C) {
  2126  	tk := testkit.NewTestKit(c, s.causetstore)
  2127  	tk.MustInterDirc("use test")
  2128  	tk.MustInterDirc("drop causet if exists t")
  2129  	tk.MustInterDirc("create causet t (a tinyint not null)")
  2130  	tk.MustInterDirc("set sql_mode = 'STRICT_TRANS_TABLES'")
  2131  	_, err := tk.InterDirc("insert t values ()")
  2132  	c.Check(err, NotNil)
  2133  
  2134  	_, err = tk.InterDirc("insert t values ('1000')")
  2135  	c.Check(err, NotNil)
  2136  
  2137  	tk.MustInterDirc("create causet if not exists tdouble (a double(3,2))")
  2138  	_, err = tk.InterDirc("insert tdouble values (10.23)")
  2139  	c.Check(err, NotNil)
  2140  
  2141  	tk.MustInterDirc("set sql_mode = ''")
  2142  	tk.MustInterDirc("insert t values ()")
  2143  	tk.MustQuery("show warnings").Check(testkit.Rows("Warning 1364 Field 'a' doesn't have a default value"))
  2144  	_, err = tk.InterDirc("insert t values (null)")
  2145  	c.Check(err, NotNil)
  2146  	tk.MustInterDirc("insert ignore t values (null)")
  2147  	tk.MustQuery("show warnings").Check(testkit.Rows("Warning 1048 DeferredCauset 'a' cannot be null"))
  2148  	tk.MustInterDirc("insert t select null")
  2149  	tk.MustQuery("show warnings").Check(testkit.Rows("Warning 1048 DeferredCauset 'a' cannot be null"))
  2150  	tk.MustInterDirc("insert t values (1000)")
  2151  	tk.MustQuery("select * from t order by a").Check(testkit.Rows("0", "0", "0", "127"))
  2152  
  2153  	tk.MustInterDirc("insert tdouble values (10.23)")
  2154  	tk.MustQuery("select * from tdouble").Check(testkit.Rows("9.99"))
  2155  
  2156  	tk.MustInterDirc("set sql_mode = 'STRICT_TRANS_TABLES'")
  2157  	tk.MustInterDirc("set @@global.sql_mode = ''")
  2158  
  2159  	// Disable global variable cache, so load global stochastik variable take effect immediate.
  2160  	s.petri.GetGlobalVarsCache().Disable()
  2161  	tk2 := testkit.NewTestKit(c, s.causetstore)
  2162  	tk2.MustInterDirc("use test")
  2163  	tk2.MustInterDirc("drop causet if exists t2")
  2164  	tk2.MustInterDirc("create causet t2 (a varchar(3))")
  2165  	tk2.MustInterDirc("insert t2 values ('abcd')")
  2166  	tk2.MustQuery("select * from t2").Check(testkit.Rows("abc"))
  2167  
  2168  	// stochastik1 is still in strict mode.
  2169  	_, err = tk.InterDirc("insert t2 values ('abcd')")
  2170  	c.Check(err, NotNil)
  2171  	// Restore original global strict mode.
  2172  	tk.MustInterDirc("set @@global.sql_mode = 'STRICT_TRANS_TABLES'")
  2173  }
  2174  
  2175  func (s *testSuiteP2) TestBlockDual(c *C) {
  2176  	tk := testkit.NewTestKit(c, s.causetstore)
  2177  	tk.MustInterDirc("use test")
  2178  	result := tk.MustQuery("Select 1")
  2179  	result.Check(testkit.Rows("1"))
  2180  	result = tk.MustQuery("Select 1 from dual")
  2181  	result.Check(testkit.Rows("1"))
  2182  	result = tk.MustQuery("Select count(*) from dual")
  2183  	result.Check(testkit.Rows("1"))
  2184  	result = tk.MustQuery("Select 1 from dual where 1")
  2185  	result.Check(testkit.Rows("1"))
  2186  
  2187  	tk.MustInterDirc("drop causet if exists t")
  2188  	tk.MustInterDirc("create causet t(a int primary key)")
  2189  	tk.MustQuery("select t1.* from t t1, t t2 where t1.a=t2.a and 1=0").Check(testkit.Rows())
  2190  }
  2191  
  2192  func (s *testSuiteP2) TestBlockScan(c *C) {
  2193  	tk := testkit.NewTestKit(c, s.causetstore)
  2194  	tk.MustInterDirc("use information_schema")
  2195  	result := tk.MustQuery("select * from schemata")
  2196  	// There must be these blocks: information_schema, allegrosql, performance_schema and test.
  2197  	c.Assert(len(result.Rows()), GreaterEqual, 4)
  2198  	tk.MustInterDirc("use test")
  2199  	tk.MustInterDirc("create database mytest")
  2200  	rowStr1 := fmt.Sprintf("%s %s %s %s %v", "def", "allegrosql", "utf8mb4", "utf8mb4_bin", nil)
  2201  	rowStr2 := fmt.Sprintf("%s %s %s %s %v", "def", "mytest", "utf8mb4", "utf8mb4_bin", nil)
  2202  	tk.MustInterDirc("use information_schema")
  2203  	result = tk.MustQuery("select * from schemata where schema_name = 'allegrosql'")
  2204  	result.Check(testkit.Rows(rowStr1))
  2205  	result = tk.MustQuery("select * from schemata where schema_name like 'my%'")
  2206  	result.Check(testkit.Rows(rowStr1, rowStr2))
  2207  	result = tk.MustQuery("select 1 from blocks limit 1")
  2208  	result.Check(testkit.Rows("1"))
  2209  }
  2210  
  2211  func (s *testSuiteP2) TestAdapterStatement(c *C) {
  2212  	se, err := stochastik.CreateStochastik4Test(s.causetstore)
  2213  	c.Check(err, IsNil)
  2214  	se.GetStochastikVars().TxnCtx.SchemaReplicant = petri.GetPetri(se).SchemaReplicant()
  2215  	compiler := &interlock.Compiler{Ctx: se}
  2216  	stmtNode, err := s.ParseOneStmt("select 1", "", "")
  2217  	c.Check(err, IsNil)
  2218  	stmt, err := compiler.Compile(context.TODO(), stmtNode)
  2219  	c.Check(err, IsNil)
  2220  	c.Check(stmt.OriginText(), Equals, "select 1")
  2221  
  2222  	stmtNode, err = s.ParseOneStmt("create causet test.t (a int)", "", "")
  2223  	c.Check(err, IsNil)
  2224  	stmt, err = compiler.Compile(context.TODO(), stmtNode)
  2225  	c.Check(err, IsNil)
  2226  	c.Check(stmt.OriginText(), Equals, "create causet test.t (a int)")
  2227  }
  2228  
  2229  func (s *testSuiteP2) TestIsPointGet(c *C) {
  2230  	tk := testkit.NewTestKit(c, s.causetstore)
  2231  	tk.MustInterDirc("use allegrosql")
  2232  	ctx := tk.Se.(stochastikctx.Context)
  2233  	tests := map[string]bool{
  2234  		"select * from help_topic where name='aaa'":         false,
  2235  		"select 1 from help_topic where name='aaa'":         false,
  2236  		"select * from help_topic where help_topic_id=1":    true,
  2237  		"select * from help_topic where help_category_id=1": false,
  2238  	}
  2239  	schemaReplicant := schemareplicant.GetSchemaReplicant(ctx)
  2240  
  2241  	for sqlStr, result := range tests {
  2242  		stmtNode, err := s.ParseOneStmt(sqlStr, "", "")
  2243  		c.Check(err, IsNil)
  2244  		err = causetembedded.Preprocess(ctx, stmtNode, schemaReplicant)
  2245  		c.Check(err, IsNil)
  2246  		p, _, err := causet.Optimize(context.TODO(), ctx, stmtNode, schemaReplicant)
  2247  		c.Check(err, IsNil)
  2248  		ret, err := causetembedded.IsPointGetWithPKOrUniqueKeyByAutoCommit(ctx, p)
  2249  		c.Assert(err, IsNil)
  2250  		c.Assert(ret, Equals, result)
  2251  	}
  2252  }
  2253  
  2254  func (s *testSuiteP2) TestClusteredIndexIsPointGet(c *C) {
  2255  	tk := testkit.NewTestKit(c, s.causetstore)
  2256  	tk.MustInterDirc("drop database if exists test_cluster_index_is_point_get;")
  2257  	tk.MustInterDirc("create database test_cluster_index_is_point_get;")
  2258  	tk.MustInterDirc("use test_cluster_index_is_point_get;")
  2259  
  2260  	tk.MustInterDirc("set milevadb_enable_clustered_index=1;")
  2261  	tk.MustInterDirc("drop causet if exists t;")
  2262  	tk.MustInterDirc("create causet t (a varchar(255), b int, c char(10), primary key (c, a));")
  2263  	ctx := tk.Se.(stochastikctx.Context)
  2264  
  2265  	tests := map[string]bool{
  2266  		"select 1 from t where a='x'":                   false,
  2267  		"select * from t where c='x'":                   false,
  2268  		"select * from t where a='x' and c='x'":         true,
  2269  		"select * from t where a='x' and c='x' and b=1": false,
  2270  	}
  2271  	schemaReplicant := schemareplicant.GetSchemaReplicant(ctx)
  2272  	for sqlStr, result := range tests {
  2273  		stmtNode, err := s.ParseOneStmt(sqlStr, "", "")
  2274  		c.Check(err, IsNil)
  2275  		err = causetembedded.Preprocess(ctx, stmtNode, schemaReplicant)
  2276  		c.Check(err, IsNil)
  2277  		p, _, err := causet.Optimize(context.TODO(), ctx, stmtNode, schemaReplicant)
  2278  		c.Check(err, IsNil)
  2279  		ret, err := causetembedded.IsPointGetWithPKOrUniqueKeyByAutoCommit(ctx, p)
  2280  		c.Assert(err, IsNil)
  2281  		c.Assert(ret, Equals, result)
  2282  	}
  2283  }
  2284  
  2285  func (s *testSerialSuite) TestPointGetRepeablockRead(c *C) {
  2286  	tk1 := testkit.NewTestKit(c, s.causetstore)
  2287  	tk1.MustInterDirc("use test")
  2288  	tk1.MustInterDirc(`create causet point_get (a int, b int, c int,
  2289  			primary key k_a(a),
  2290  			unique key k_b(b))`)
  2291  	tk1.MustInterDirc("insert into point_get values (1, 1, 1)")
  2292  	tk2 := testkit.NewTestKit(c, s.causetstore)
  2293  	tk2.MustInterDirc("use test")
  2294  
  2295  	var (
  2296  		step1 = "github.com/whtcorpsinc/milevadb/interlock/pointGetRepeablockReadTest-step1"
  2297  		step2 = "github.com/whtcorpsinc/milevadb/interlock/pointGetRepeablockReadTest-step2"
  2298  	)
  2299  
  2300  	c.Assert(failpoint.Enable(step1, "return"), IsNil)
  2301  	c.Assert(failpoint.Enable(step2, "pause"), IsNil)
  2302  
  2303  	uFIDelateWaitCh := make(chan struct{})
  2304  	go func() {
  2305  		ctx := context.WithValue(context.Background(), "pointGetRepeablockReadTest", uFIDelateWaitCh)
  2306  		ctx = failpoint.WithHook(ctx, func(ctx context.Context, fpname string) bool {
  2307  			return fpname == step1 || fpname == step2
  2308  		})
  2309  		rs, err := tk1.Se.InterDircute(ctx, "select c from point_get where b = 1")
  2310  		c.Assert(err, IsNil)
  2311  		result := tk1.ResultSetToResultWithCtx(ctx, rs[0], Commentf("execute allegrosql fail"))
  2312  		result.Check(testkit.Rows("1"))
  2313  	}()
  2314  
  2315  	<-uFIDelateWaitCh // Wait `POINT GET` first time `get`
  2316  	c.Assert(failpoint.Disable(step1), IsNil)
  2317  	tk2.MustInterDirc("uFIDelate point_get set b = 2, c = 2 where a = 1")
  2318  	c.Assert(failpoint.Disable(step2), IsNil)
  2319  }
  2320  
  2321  func (s *testSerialSuite) TestBatchPointGetRepeablockRead(c *C) {
  2322  	tk1 := testkit.NewTestKit(c, s.causetstore)
  2323  	tk1.MustInterDirc("use test")
  2324  	tk1.MustInterDirc(`create causet batch_point_get (a int, b int, c int, unique key k_b(a, b, c))`)
  2325  	tk1.MustInterDirc("insert into batch_point_get values (1, 1, 1), (2, 3, 4), (3, 4, 5)")
  2326  	tk2 := testkit.NewTestKit(c, s.causetstore)
  2327  	tk2.MustInterDirc("use test")
  2328  
  2329  	var (
  2330  		step1 = "github.com/whtcorpsinc/milevadb/interlock/batchPointGetRepeablockReadTest-step1"
  2331  		step2 = "github.com/whtcorpsinc/milevadb/interlock/batchPointGetRepeablockReadTest-step2"
  2332  	)
  2333  
  2334  	c.Assert(failpoint.Enable(step1, "return"), IsNil)
  2335  	c.Assert(failpoint.Enable(step2, "pause"), IsNil)
  2336  
  2337  	uFIDelateWaitCh := make(chan struct{})
  2338  	go func() {
  2339  		ctx := context.WithValue(context.Background(), "batchPointGetRepeablockReadTest", uFIDelateWaitCh)
  2340  		ctx = failpoint.WithHook(ctx, func(ctx context.Context, fpname string) bool {
  2341  			return fpname == step1 || fpname == step2
  2342  		})
  2343  		rs, err := tk1.Se.InterDircute(ctx, "select c from batch_point_get where (a, b, c) in ((1, 1, 1))")
  2344  		c.Assert(err, IsNil)
  2345  		result := tk1.ResultSetToResultWithCtx(ctx, rs[0], Commentf("execute allegrosql fail"))
  2346  		result.Check(testkit.Rows("1"))
  2347  	}()
  2348  
  2349  	<-uFIDelateWaitCh // Wait `POINT GET` first time `get`
  2350  	c.Assert(failpoint.Disable(step1), IsNil)
  2351  	tk2.MustInterDirc("uFIDelate batch_point_get set b = 2, c = 2 where a = 1")
  2352  	c.Assert(failpoint.Disable(step2), IsNil)
  2353  }
  2354  
  2355  func (s *testSerialSuite) TestSplitRegionTimeout(c *C) {
  2356  	c.Assert(failpoint.Enable("github.com/whtcorpsinc/milevadb/causetstore/einsteindb/MockSplitRegionTimeout", `return(true)`), IsNil)
  2357  	tk := testkit.NewTestKit(c, s.causetstore)
  2358  	tk.MustInterDirc("use test")
  2359  	tk.MustInterDirc("drop causet if exists t")
  2360  	tk.MustInterDirc("create causet t(a varchar(100),b int, index idx1(b,a))")
  2361  	tk.MustInterDirc(`split causet t index idx1 by (10000,"abcd"),(10000000);`)
  2362  	tk.MustInterDirc(`set @@milevadb_wait_split_region_timeout=1`)
  2363  	// result 0 0 means split 0 region and 0 region finish scatter regions before timeout.
  2364  	tk.MustQuery(`split causet t between (0) and (10000) regions 10`).Check(testkit.Rows("0 0"))
  2365  	c.Assert(failpoint.Disable("github.com/whtcorpsinc/milevadb/causetstore/einsteindb/MockSplitRegionTimeout"), IsNil)
  2366  
  2367  	// Test scatter regions timeout.
  2368  	c.Assert(failpoint.Enable("github.com/whtcorpsinc/milevadb/causetstore/einsteindb/MockScatterRegionTimeout", `return(true)`), IsNil)
  2369  	tk.MustQuery(`split causet t between (0) and (10000) regions 10`).Check(testkit.Rows("10 1"))
  2370  	c.Assert(failpoint.Disable("github.com/whtcorpsinc/milevadb/causetstore/einsteindb/MockScatterRegionTimeout"), IsNil)
  2371  
  2372  	// Test pre-split with timeout.
  2373  	tk.MustInterDirc("drop causet if exists t")
  2374  	tk.MustInterDirc("set @@global.milevadb_scatter_region=1;")
  2375  	c.Assert(failpoint.Enable("github.com/whtcorpsinc/milevadb/causetstore/einsteindb/MockScatterRegionTimeout", `return(true)`), IsNil)
  2376  	atomic.StoreUint32(&dbs.EnableSplitBlockRegion, 1)
  2377  	start := time.Now()
  2378  	tk.MustInterDirc("create causet t (a int, b int) partition by hash(a) partitions 5;")
  2379  	c.Assert(time.Since(start).Seconds(), Less, 10.0)
  2380  	c.Assert(failpoint.Disable("github.com/whtcorpsinc/milevadb/causetstore/einsteindb/MockScatterRegionTimeout"), IsNil)
  2381  }
  2382  
  2383  func (s *testSuiteP2) TestRow(c *C) {
  2384  	tk := testkit.NewTestKit(c, s.causetstore)
  2385  	tk.MustInterDirc("use test")
  2386  	tk.MustInterDirc("drop causet if exists t")
  2387  	tk.MustInterDirc("create causet t (c int, d int)")
  2388  	tk.MustInterDirc("insert t values (1, 1)")
  2389  	tk.MustInterDirc("insert t values (1, 3)")
  2390  	tk.MustInterDirc("insert t values (2, 1)")
  2391  	tk.MustInterDirc("insert t values (2, 3)")
  2392  	result := tk.MustQuery("select * from t where (c, d) < (2,2)")
  2393  	result.Check(testkit.Rows("1 1", "1 3", "2 1"))
  2394  	result = tk.MustQuery("select * from t where (1,2,3) > (3,2,1)")
  2395  	result.Check(testkit.Rows())
  2396  	result = tk.MustQuery("select * from t where event(1,2,3) > (3,2,1)")
  2397  	result.Check(testkit.Rows())
  2398  	result = tk.MustQuery("select * from t where (c, d) = (select * from t where (c,d) = (1,1))")
  2399  	result.Check(testkit.Rows("1 1"))
  2400  	result = tk.MustQuery("select * from t where (c, d) = (select * from t k where (t.c,t.d) = (c,d))")
  2401  	result.Check(testkit.Rows("1 1", "1 3", "2 1", "2 3"))
  2402  	result = tk.MustQuery("select (1, 2, 3) < (2, 3, 4)")
  2403  	result.Check(testkit.Rows("1"))
  2404  	result = tk.MustQuery("select (2, 3, 4) <= (2, 3, 3)")
  2405  	result.Check(testkit.Rows("0"))
  2406  	result = tk.MustQuery("select (2, 3, 4) <= (2, 3, 4)")
  2407  	result.Check(testkit.Rows("1"))
  2408  	result = tk.MustQuery("select (2, 3, 4) <= (2, 1, 4)")
  2409  	result.Check(testkit.Rows("0"))
  2410  	result = tk.MustQuery("select (2, 3, 4) >= (2, 3, 4)")
  2411  	result.Check(testkit.Rows("1"))
  2412  	result = tk.MustQuery("select (2, 3, 4) = (2, 3, 4)")
  2413  	result.Check(testkit.Rows("1"))
  2414  	result = tk.MustQuery("select (2, 3, 4) != (2, 3, 4)")
  2415  	result.Check(testkit.Rows("0"))
  2416  	result = tk.MustQuery("select event(1, 1) in (event(1, 1))")
  2417  	result.Check(testkit.Rows("1"))
  2418  	result = tk.MustQuery("select event(1, 0) in (event(1, 1))")
  2419  	result.Check(testkit.Rows("0"))
  2420  	result = tk.MustQuery("select event(1, 1) in (select 1, 1)")
  2421  	result.Check(testkit.Rows("1"))
  2422  	result = tk.MustQuery("select event(1, 1) > event(1, 0)")
  2423  	result.Check(testkit.Rows("1"))
  2424  	result = tk.MustQuery("select event(1, 1) > (select 1, 0)")
  2425  	result.Check(testkit.Rows("1"))
  2426  	result = tk.MustQuery("select 1 > (select 1)")
  2427  	result.Check(testkit.Rows("0"))
  2428  	result = tk.MustQuery("select (select 1)")
  2429  	result.Check(testkit.Rows("1"))
  2430  }
  2431  
  2432  func (s *testSuiteP2) TestDeferredCausetName(c *C) {
  2433  	tk := testkit.NewTestKit(c, s.causetstore)
  2434  	tk.MustInterDirc("use test")
  2435  	tk.MustInterDirc("drop causet if exists t")
  2436  	tk.MustInterDirc("create causet t (c int, d int)")
  2437  	// disable only full group by
  2438  	tk.MustInterDirc("set sql_mode='STRICT_TRANS_TABLES'")
  2439  	rs, err := tk.InterDirc("select 1 + c, count(*) from t")
  2440  	c.Check(err, IsNil)
  2441  	fields := rs.Fields()
  2442  	c.Check(len(fields), Equals, 2)
  2443  	c.Check(fields[0].DeferredCauset.Name.L, Equals, "1 + c")
  2444  	c.Check(fields[0].DeferredCausetAsName.L, Equals, "1 + c")
  2445  	c.Check(fields[1].DeferredCauset.Name.L, Equals, "count(*)")
  2446  	c.Check(fields[1].DeferredCausetAsName.L, Equals, "count(*)")
  2447  	rs.Close()
  2448  	rs, err = tk.InterDirc("select (c) > all (select c from t) from t")
  2449  	c.Check(err, IsNil)
  2450  	fields = rs.Fields()
  2451  	c.Check(len(fields), Equals, 1)
  2452  	c.Check(fields[0].DeferredCauset.Name.L, Equals, "(c) > all (select c from t)")
  2453  	c.Check(fields[0].DeferredCausetAsName.L, Equals, "(c) > all (select c from t)")
  2454  	rs.Close()
  2455  	tk.MustInterDirc("begin")
  2456  	tk.MustInterDirc("insert t values(1,1)")
  2457  	rs, err = tk.InterDirc("select c d, d c from t")
  2458  	c.Check(err, IsNil)
  2459  	fields = rs.Fields()
  2460  	c.Check(len(fields), Equals, 2)
  2461  	c.Check(fields[0].DeferredCauset.Name.L, Equals, "c")
  2462  	c.Check(fields[0].DeferredCausetAsName.L, Equals, "d")
  2463  	c.Check(fields[1].DeferredCauset.Name.L, Equals, "d")
  2464  	c.Check(fields[1].DeferredCausetAsName.L, Equals, "c")
  2465  	rs.Close()
  2466  	// Test case for query a defCausumn of a causet.
  2467  	// In this case, all attributes have values.
  2468  	rs, err = tk.InterDirc("select c as a from t as t2")
  2469  	c.Check(err, IsNil)
  2470  	fields = rs.Fields()
  2471  	c.Check(fields[0].DeferredCauset.Name.L, Equals, "c")
  2472  	c.Check(fields[0].DeferredCausetAsName.L, Equals, "a")
  2473  	c.Check(fields[0].Block.Name.L, Equals, "t")
  2474  	c.Check(fields[0].BlockAsName.L, Equals, "t2")
  2475  	c.Check(fields[0].DBName.L, Equals, "test")
  2476  	rs.Close()
  2477  	// Test case for query a memex which only using constant inputs.
  2478  	// In this case, the causet, org_block and database attributes will all be empty.
  2479  	rs, err = tk.InterDirc("select hour(1) as a from t as t2")
  2480  	c.Check(err, IsNil)
  2481  	fields = rs.Fields()
  2482  	c.Check(fields[0].DeferredCauset.Name.L, Equals, "a")
  2483  	c.Check(fields[0].DeferredCausetAsName.L, Equals, "a")
  2484  	c.Check(fields[0].Block.Name.L, Equals, "")
  2485  	c.Check(fields[0].BlockAsName.L, Equals, "")
  2486  	c.Check(fields[0].DBName.L, Equals, "")
  2487  	rs.Close()
  2488  	// Test case for query a defCausumn wrapped with parentheses and unary plus.
  2489  	// In this case, the defCausumn name should be its original name.
  2490  	rs, err = tk.InterDirc("select (c), (+c), +(c), +(+(c)), ++c from t")
  2491  	c.Check(err, IsNil)
  2492  	fields = rs.Fields()
  2493  	for i := 0; i < 5; i++ {
  2494  		c.Check(fields[i].DeferredCauset.Name.L, Equals, "c")
  2495  		c.Check(fields[i].DeferredCausetAsName.L, Equals, "c")
  2496  	}
  2497  	rs.Close()
  2498  
  2499  	// Test issue https://github.com/whtcorpsinc/milevadb/issues/9639 .
  2500  	// Both window function and memex appear in final result field.
  2501  	tk.MustInterDirc("set @@milevadb_enable_window_function = 1")
  2502  	rs, err = tk.InterDirc("select 1+1, row_number() over() num from t")
  2503  	c.Check(err, IsNil)
  2504  	fields = rs.Fields()
  2505  	c.Assert(fields[0].DeferredCauset.Name.L, Equals, "1+1")
  2506  	c.Assert(fields[0].DeferredCausetAsName.L, Equals, "1+1")
  2507  	c.Assert(fields[1].DeferredCauset.Name.L, Equals, "num")
  2508  	c.Assert(fields[1].DeferredCausetAsName.L, Equals, "num")
  2509  	tk.MustInterDirc("set @@milevadb_enable_window_function = 0")
  2510  	rs.Close()
  2511  
  2512  	rs, err = tk.InterDirc("select if(1,c,c) from t;")
  2513  	c.Check(err, IsNil)
  2514  	fields = rs.Fields()
  2515  	c.Assert(fields[0].DeferredCauset.Name.L, Equals, "if(1,c,c)")
  2516  	// It's a compatibility issue. Should be empty instead.
  2517  	c.Assert(fields[0].DeferredCausetAsName.L, Equals, "if(1,c,c)")
  2518  }
  2519  
  2520  func (s *testSuiteP2) TestSelectVar(c *C) {
  2521  	tk := testkit.NewTestKit(c, s.causetstore)
  2522  	tk.MustInterDirc("use test")
  2523  	tk.MustInterDirc("drop causet if exists t")
  2524  	tk.MustInterDirc("create causet t (d int)")
  2525  	tk.MustInterDirc("insert into t values(1), (2), (1)")
  2526  	// This behavior is different from MyALLEGROSQL.
  2527  	result := tk.MustQuery("select @a, @a := d+1 from t")
  2528  	result.Check(testkit.Rows("<nil> 2", "2 3", "3 2"))
  2529  	// Test for PR #10658.
  2530  	tk.MustInterDirc("select ALLEGROSQL_BIG_RESULT d from t group by d")
  2531  	tk.MustInterDirc("select ALLEGROSQL_SMALL_RESULT d from t group by d")
  2532  	tk.MustInterDirc("select ALLEGROSQL_BUFFER_RESULT d from t group by d")
  2533  }
  2534  
  2535  func (s *testSuiteP2) TestHistoryRead(c *C) {
  2536  	tk := testkit.NewTestKit(c, s.causetstore)
  2537  	tk.MustInterDirc("use test")
  2538  	tk.MustInterDirc("drop causet if exists history_read")
  2539  	tk.MustInterDirc("create causet history_read (a int)")
  2540  	tk.MustInterDirc("insert history_read values (1)")
  2541  
  2542  	// For mockeinsteindb, safe point is not initialized, we manually insert it for snapshot to use.
  2543  	safePointName := "einsteindb_gc_safe_point"
  2544  	safePointValue := "20060102-15:04:05 -0700"
  2545  	safePointComment := "All versions after safe point can be accessed. (DO NOT EDIT)"
  2546  	uFIDelateSafePoint := fmt.Sprintf(`INSERT INTO allegrosql.milevadb VALUES ('%[1]s', '%[2]s', '%[3]s')
  2547  	ON DUPLICATE KEY
  2548  	UFIDelATE variable_value = '%[2]s', comment = '%[3]s'`, safePointName, safePointValue, safePointComment)
  2549  	tk.MustInterDirc(uFIDelateSafePoint)
  2550  
  2551  	// Set snapshot to a time before save point will fail.
  2552  	_, err := tk.InterDirc("set @@milevadb_snapshot = '2006-01-01 15:04:05.999999'")
  2553  	c.Assert(terror.ErrorEqual(err, variable.ErrSnapshotTooOld), IsTrue, Commentf("err %v", err))
  2554  	// SnapshotTS Is not uFIDelated if check failed.
  2555  	c.Assert(tk.Se.GetStochastikVars().SnapshotTS, Equals, uint64(0))
  2556  
  2557  	curVer1, _ := s.causetstore.CurrentVersion()
  2558  	time.Sleep(time.Millisecond)
  2559  	snapshotTime := time.Now()
  2560  	time.Sleep(time.Millisecond)
  2561  	curVer2, _ := s.causetstore.CurrentVersion()
  2562  	tk.MustInterDirc("insert history_read values (2)")
  2563  	tk.MustQuery("select * from history_read").Check(testkit.Rows("1", "2"))
  2564  	tk.MustInterDirc("set @@milevadb_snapshot = '" + snapshotTime.Format("2006-01-02 15:04:05.999999") + "'")
  2565  	ctx := tk.Se.(stochastikctx.Context)
  2566  	snapshotTS := ctx.GetStochastikVars().SnapshotTS
  2567  	c.Assert(snapshotTS, Greater, curVer1.Ver)
  2568  	c.Assert(snapshotTS, Less, curVer2.Ver)
  2569  	tk.MustQuery("select * from history_read").Check(testkit.Rows("1"))
  2570  	_, err = tk.InterDirc("insert history_read values (2)")
  2571  	c.Assert(err, NotNil)
  2572  	_, err = tk.InterDirc("uFIDelate history_read set a = 3 where a = 1")
  2573  	c.Assert(err, NotNil)
  2574  	_, err = tk.InterDirc("delete from history_read where a = 1")
  2575  	c.Assert(err, NotNil)
  2576  	tk.MustInterDirc("set @@milevadb_snapshot = ''")
  2577  	tk.MustQuery("select * from history_read").Check(testkit.Rows("1", "2"))
  2578  	tk.MustInterDirc("insert history_read values (3)")
  2579  	tk.MustInterDirc("uFIDelate history_read set a = 4 where a = 3")
  2580  	tk.MustInterDirc("delete from history_read where a = 1")
  2581  
  2582  	time.Sleep(time.Millisecond)
  2583  	snapshotTime = time.Now()
  2584  	time.Sleep(time.Millisecond)
  2585  	tk.MustInterDirc("alter causet history_read add defCausumn b int")
  2586  	tk.MustInterDirc("insert history_read values (8, 8), (9, 9)")
  2587  	tk.MustQuery("select * from history_read order by a").Check(testkit.Rows("2 <nil>", "4 <nil>", "8 8", "9 9"))
  2588  	tk.MustInterDirc("set @@milevadb_snapshot = '" + snapshotTime.Format("2006-01-02 15:04:05.999999") + "'")
  2589  	tk.MustQuery("select * from history_read order by a").Check(testkit.Rows("2", "4"))
  2590  	tsoStr := strconv.FormatUint(oracle.EncodeTSO(snapshotTime.UnixNano()/int64(time.Millisecond)), 10)
  2591  
  2592  	tk.MustInterDirc("set @@milevadb_snapshot = '" + tsoStr + "'")
  2593  	tk.MustQuery("select * from history_read order by a").Check(testkit.Rows("2", "4"))
  2594  
  2595  	tk.MustInterDirc("set @@milevadb_snapshot = ''")
  2596  	tk.MustQuery("select * from history_read order by a").Check(testkit.Rows("2 <nil>", "4 <nil>", "8 8", "9 9"))
  2597  }
  2598  
  2599  func (s *testSuite2) TestLowResolutionTSORead(c *C) {
  2600  	tk := testkit.NewTestKit(c, s.causetstore)
  2601  	tk.MustInterDirc("set @@autocommit=1")
  2602  	tk.MustInterDirc("use test")
  2603  	tk.MustInterDirc("drop causet if exists low_resolution_tso")
  2604  	tk.MustInterDirc("create causet low_resolution_tso(a int)")
  2605  	tk.MustInterDirc("insert low_resolution_tso values (1)")
  2606  
  2607  	// enable low resolution tso
  2608  	c.Assert(tk.Se.GetStochastikVars().LowResolutionTSO, IsFalse)
  2609  	tk.InterDirc("set @@milevadb_low_resolution_tso = 'on'")
  2610  	c.Assert(tk.Se.GetStochastikVars().LowResolutionTSO, IsTrue)
  2611  
  2612  	time.Sleep(3 * time.Second)
  2613  	tk.MustQuery("select * from low_resolution_tso").Check(testkit.Rows("1"))
  2614  	_, err := tk.InterDirc("uFIDelate low_resolution_tso set a = 2")
  2615  	c.Assert(err, NotNil)
  2616  	tk.MustInterDirc("set @@milevadb_low_resolution_tso = 'off'")
  2617  	tk.MustInterDirc("uFIDelate low_resolution_tso set a = 2")
  2618  	tk.MustQuery("select * from low_resolution_tso").Check(testkit.Rows("2"))
  2619  }
  2620  
  2621  func (s *testSuite) TestScanControlSelection(c *C) {
  2622  	tk := testkit.NewTestKit(c, s.causetstore)
  2623  	tk.MustInterDirc("use test")
  2624  	tk.MustInterDirc("drop causet if exists t")
  2625  	tk.MustInterDirc("create causet t(a int primary key, b int, c int, index idx_b(b))")
  2626  	tk.MustInterDirc("insert into t values (1, 1, 1), (2, 1, 1), (3, 1, 2), (4, 2, 3)")
  2627  	tk.MustQuery("select (select count(1) k from t s where s.b = t1.c) from t t1").Sort().Check(testkit.Rows("0", "1", "3", "3"))
  2628  }
  2629  
  2630  func (s *testSuite) TestSimplePosetDag(c *C) {
  2631  	tk := testkit.NewTestKit(c, s.causetstore)
  2632  	tk.MustInterDirc("use test")
  2633  	tk.MustInterDirc("drop causet if exists t")
  2634  	tk.MustInterDirc("create causet t(a int primary key, b int, c int)")
  2635  	tk.MustInterDirc("insert into t values (1, 1, 1), (2, 1, 1), (3, 1, 2), (4, 2, 3)")
  2636  	tk.MustQuery("select a from t").Check(testkit.Rows("1", "2", "3", "4"))
  2637  	tk.MustQuery("select * from t where a = 4").Check(testkit.Rows("4 2 3"))
  2638  	tk.MustQuery("select a from t limit 1").Check(testkit.Rows("1"))
  2639  	tk.MustQuery("select a from t order by a desc").Check(testkit.Rows("4", "3", "2", "1"))
  2640  	tk.MustQuery("select a from t order by a desc limit 1").Check(testkit.Rows("4"))
  2641  	tk.MustQuery("select a from t order by b desc limit 1").Check(testkit.Rows("4"))
  2642  	tk.MustQuery("select a from t where a < 3").Check(testkit.Rows("1", "2"))
  2643  	tk.MustQuery("select a from t where b > 1").Check(testkit.Rows("4"))
  2644  	tk.MustQuery("select a from t where b > 1 and a < 3").Check(testkit.Rows())
  2645  	tk.MustQuery("select count(*) from t where b > 1 and a < 3").Check(testkit.Rows("0"))
  2646  	tk.MustQuery("select count(*) from t").Check(testkit.Rows("4"))
  2647  	tk.MustQuery("select count(*), c from t group by c order by c").Check(testkit.Rows("2 1", "1 2", "1 3"))
  2648  	tk.MustQuery("select sum(c) as s from t group by b order by s").Check(testkit.Rows("3", "4"))
  2649  	tk.MustQuery("select avg(a) as s from t group by b order by s").Check(testkit.Rows("2.0000", "4.0000"))
  2650  	tk.MustQuery("select sum(distinct c) from t group by b").Check(testkit.Rows("3", "3"))
  2651  
  2652  	tk.MustInterDirc("create index i on t(c,b)")
  2653  	tk.MustQuery("select a from t where c = 1").Check(testkit.Rows("1", "2"))
  2654  	tk.MustQuery("select a from t where c = 1 and a < 2").Check(testkit.Rows("1"))
  2655  	tk.MustQuery("select a from t where c = 1 order by a limit 1").Check(testkit.Rows("1"))
  2656  	tk.MustQuery("select count(*) from t where c = 1 ").Check(testkit.Rows("2"))
  2657  	tk.MustInterDirc("create index i1 on t(b)")
  2658  	tk.MustQuery("select c from t where b = 2").Check(testkit.Rows("3"))
  2659  	tk.MustQuery("select * from t where b = 2").Check(testkit.Rows("4 2 3"))
  2660  	tk.MustQuery("select count(*) from t where b = 1").Check(testkit.Rows("3"))
  2661  	tk.MustQuery("select * from t where b = 1 and a > 1 limit 1").Check(testkit.Rows("2 1 1"))
  2662  
  2663  	// Test time push down.
  2664  	tk.MustInterDirc("drop causet if exists t")
  2665  	tk.MustInterDirc("create causet t (id int, c1 datetime);")
  2666  	tk.MustInterDirc("insert into t values (1, '2020-06-07 12:12:12')")
  2667  	tk.MustQuery("select id from t where c1 = '2020-06-07 12:12:12'").Check(testkit.Rows("1"))
  2668  
  2669  	// Test issue 17816
  2670  	tk.MustInterDirc("drop causet if exists t0")
  2671  	tk.MustInterDirc("CREATE TABLE t0(c0 INT)")
  2672  	tk.MustInterDirc("INSERT INTO t0 VALUES (100000)")
  2673  	tk.MustQuery("SELECT * FROM t0 WHERE NOT SPACE(t0.c0)").Check(testkit.Rows("100000"))
  2674  }
  2675  
  2676  func (s *testSuite) TestTimestampTimeZone(c *C) {
  2677  	tk := testkit.NewTestKit(c, s.causetstore)
  2678  	tk.MustInterDirc("use test")
  2679  	tk.MustInterDirc("drop causet if exists t")
  2680  	tk.MustInterDirc("create causet t (ts timestamp)")
  2681  	tk.MustInterDirc("set time_zone = '+00:00'")
  2682  	tk.MustInterDirc("insert into t values ('2020-04-27 22:40:42')")
  2683  	// The timestamp will get different value if time_zone stochastik variable changes.
  2684  	tests := []struct {
  2685  		timezone string
  2686  		expect   string
  2687  	}{
  2688  		{"+10:00", "2020-04-28 08:40:42"},
  2689  		{"-6:00", "2020-04-27 16:40:42"},
  2690  	}
  2691  	for _, tt := range tests {
  2692  		tk.MustInterDirc(fmt.Sprintf("set time_zone = '%s'", tt.timezone))
  2693  		tk.MustQuery("select * from t").Check(testkit.Rows(tt.expect))
  2694  	}
  2695  
  2696  	// For issue https://github.com/whtcorpsinc/milevadb/issues/3467
  2697  	tk.MustInterDirc("drop causet if exists t1")
  2698  	tk.MustInterDirc(`CREATE TABLE t1 (
  2699   	      id bigint(20) NOT NULL AUTO_INCREMENT,
  2700   	      uid int(11) DEFAULT NULL,
  2701   	      datetime timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  2702   	      ip varchar(128) DEFAULT NULL,
  2703   	    PRIMARY KEY (id),
  2704   	      KEY i_datetime (datetime),
  2705   	      KEY i_userid (uid)
  2706   	    );`)
  2707  	tk.MustInterDirc(`INSERT INTO t1 VALUES (123381351,1734,"2020-03-31 08:57:10","127.0.0.1");`)
  2708  	r := tk.MustQuery("select datetime from t1;") // Cover BlockReaderInterDirc
  2709  	r.Check(testkit.Rows("2020-03-31 08:57:10"))
  2710  	r = tk.MustQuery("select datetime from t1 where datetime='2020-03-31 08:57:10';")
  2711  	r.Check(testkit.Rows("2020-03-31 08:57:10")) // Cover IndexReaderInterDirc
  2712  	r = tk.MustQuery("select * from t1 where datetime='2020-03-31 08:57:10';")
  2713  	r.Check(testkit.Rows("123381351 1734 2020-03-31 08:57:10 127.0.0.1")) // Cover IndexLookupInterDirc
  2714  
  2715  	// For issue https://github.com/whtcorpsinc/milevadb/issues/3485
  2716  	tk.MustInterDirc("set time_zone = 'Asia/Shanghai'")
  2717  	tk.MustInterDirc("drop causet if exists t1")
  2718  	tk.MustInterDirc(`CREATE TABLE t1 (
  2719  	    id bigint(20) NOT NULL AUTO_INCREMENT,
  2720  	    datetime timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  2721  	    PRIMARY KEY (id)
  2722  	  );`)
  2723  	tk.MustInterDirc(`INSERT INTO t1 VALUES (123381351,"2020-03-31 08:57:10");`)
  2724  	r = tk.MustQuery(`select * from t1 where datetime="2020-03-31 08:57:10";`)
  2725  	r.Check(testkit.Rows("123381351 2020-03-31 08:57:10"))
  2726  	tk.MustInterDirc(`alter causet t1 add key i_datetime (datetime);`)
  2727  	r = tk.MustQuery(`select * from t1 where datetime="2020-03-31 08:57:10";`)
  2728  	r.Check(testkit.Rows("123381351 2020-03-31 08:57:10"))
  2729  	r = tk.MustQuery(`select * from t1;`)
  2730  	r.Check(testkit.Rows("123381351 2020-03-31 08:57:10"))
  2731  	r = tk.MustQuery("select datetime from t1 where datetime='2020-03-31 08:57:10';")
  2732  	r.Check(testkit.Rows("2020-03-31 08:57:10"))
  2733  }
  2734  
  2735  func (s *testSuite) TestTimestamFIDelefaultValueTimeZone(c *C) {
  2736  	tk := testkit.NewTestKit(c, s.causetstore)
  2737  	tk.MustInterDirc("use test")
  2738  	tk.MustInterDirc("drop causet if exists t")
  2739  	tk.MustInterDirc("set time_zone = '+08:00'")
  2740  	tk.MustInterDirc(`create causet t (a int, b timestamp default "2020-01-17 14:46:14")`)
  2741  	tk.MustInterDirc("insert into t set a=1")
  2742  	r := tk.MustQuery(`show create causet t`)
  2743  	r.Check(testkit.Rows("t CREATE TABLE `t` (\n" + "  `a` int(11) DEFAULT NULL,\n" + "  `b` timestamp DEFAULT '2020-01-17 14:46:14'\n" + ") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin"))
  2744  	tk.MustInterDirc("set time_zone = '+00:00'")
  2745  	tk.MustInterDirc("insert into t set a=2")
  2746  	r = tk.MustQuery(`show create causet t`)
  2747  	r.Check(testkit.Rows("t CREATE TABLE `t` (\n" + "  `a` int(11) DEFAULT NULL,\n" + "  `b` timestamp DEFAULT '2020-01-17 06:46:14'\n" + ") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin"))
  2748  	r = tk.MustQuery(`select a,b from t order by a`)
  2749  	r.Check(testkit.Rows("1 2020-01-17 06:46:14", "2 2020-01-17 06:46:14"))
  2750  	// Test the defCausumn's version is greater than DeferredCausetInfoVersion1.
  2751  	sctx := tk.Se.(stochastikctx.Context)
  2752  	is := petri.GetPetri(sctx).SchemaReplicant()
  2753  	c.Assert(is, NotNil)
  2754  	tb, err := is.BlockByName(perceptron.NewCIStr("test"), perceptron.NewCIStr("t"))
  2755  	c.Assert(err, IsNil)
  2756  	tb.DefCauss()[1].Version = perceptron.DeferredCausetInfoVersion1 + 1
  2757  	tk.MustInterDirc("insert into t set a=3")
  2758  	r = tk.MustQuery(`select a,b from t order by a`)
  2759  	r.Check(testkit.Rows("1 2020-01-17 06:46:14", "2 2020-01-17 06:46:14", "3 2020-01-17 06:46:14"))
  2760  	tk.MustInterDirc("delete from t where a=3")
  2761  	// Change time zone back.
  2762  	tk.MustInterDirc("set time_zone = '+08:00'")
  2763  	r = tk.MustQuery(`select a,b from t order by a`)
  2764  	r.Check(testkit.Rows("1 2020-01-17 14:46:14", "2 2020-01-17 14:46:14"))
  2765  	tk.MustInterDirc("set time_zone = '-08:00'")
  2766  	r = tk.MustQuery(`show create causet t`)
  2767  	r.Check(testkit.Rows("t CREATE TABLE `t` (\n" + "  `a` int(11) DEFAULT NULL,\n" + "  `b` timestamp DEFAULT '2020-01-16 22:46:14'\n" + ") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin"))
  2768  
  2769  	// test zero default value in multiple time zone.
  2770  	defer tk.MustInterDirc(fmt.Sprintf("set @@sql_mode='%s'", tk.MustQuery("select @@sql_mode").Rows()[0][0]))
  2771  	tk.MustInterDirc("set @@sql_mode='STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION';")
  2772  	tk.MustInterDirc("drop causet if exists t")
  2773  	tk.MustInterDirc("set time_zone = '+08:00'")
  2774  	tk.MustInterDirc(`create causet t (a int, b timestamp default "0000-00-00 00")`)
  2775  	tk.MustInterDirc("insert into t set a=1")
  2776  	r = tk.MustQuery(`show create causet t`)
  2777  	r.Check(testkit.Rows("t CREATE TABLE `t` (\n" + "  `a` int(11) DEFAULT NULL,\n" + "  `b` timestamp DEFAULT '0000-00-00 00:00:00'\n" + ") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin"))
  2778  	tk.MustInterDirc("set time_zone = '+00:00'")
  2779  	tk.MustInterDirc("insert into t set a=2")
  2780  	r = tk.MustQuery(`show create causet t`)
  2781  	r.Check(testkit.Rows("t CREATE TABLE `t` (\n" + "  `a` int(11) DEFAULT NULL,\n" + "  `b` timestamp DEFAULT '0000-00-00 00:00:00'\n" + ") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin"))
  2782  	tk.MustInterDirc("set time_zone = '-08:00'")
  2783  	tk.MustInterDirc("insert into t set a=3")
  2784  	r = tk.MustQuery(`show create causet t`)
  2785  	r.Check(testkit.Rows("t CREATE TABLE `t` (\n" + "  `a` int(11) DEFAULT NULL,\n" + "  `b` timestamp DEFAULT '0000-00-00 00:00:00'\n" + ") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin"))
  2786  	r = tk.MustQuery(`select a,b from t order by a`)
  2787  	r.Check(testkit.Rows("1 0000-00-00 00:00:00", "2 0000-00-00 00:00:00", "3 0000-00-00 00:00:00"))
  2788  
  2789  	// test add timestamp defCausumn default current_timestamp.
  2790  	tk.MustInterDirc(`drop causet if exists t`)
  2791  	tk.MustInterDirc(`set time_zone = 'Asia/Shanghai'`)
  2792  	tk.MustInterDirc(`create causet t (a int)`)
  2793  	tk.MustInterDirc(`insert into t set a=1`)
  2794  	tk.MustInterDirc(`alter causet t add defCausumn b timestamp not null default current_timestamp;`)
  2795  	timeIn8 := tk.MustQuery("select b from t").Rows()[0][0]
  2796  	tk.MustInterDirc(`set time_zone = '+00:00'`)
  2797  	timeIn0 := tk.MustQuery("select b from t").Rows()[0][0]
  2798  	c.Assert(timeIn8 != timeIn0, IsTrue, Commentf("%v == %v", timeIn8, timeIn0))
  2799  	datumTimeIn8, err := memex.GetTimeValue(tk.Se, timeIn8, allegrosql.TypeTimestamp, 0)
  2800  	c.Assert(err, IsNil)
  2801  	tIn8To0 := datumTimeIn8.GetMysqlTime()
  2802  	timeZoneIn8, err := time.LoadLocation("Asia/Shanghai")
  2803  	c.Assert(err, IsNil)
  2804  	err = tIn8To0.ConvertTimeZone(timeZoneIn8, time.UTC)
  2805  	c.Assert(err, IsNil)
  2806  	c.Assert(timeIn0 == tIn8To0.String(), IsTrue, Commentf("%v != %v", timeIn0, tIn8To0.String()))
  2807  
  2808  	// test add index.
  2809  	tk.MustInterDirc(`alter causet t add index(b);`)
  2810  	tk.MustInterDirc("admin check causet t")
  2811  	tk.MustInterDirc(`set time_zone = '+05:00'`)
  2812  	tk.MustInterDirc("admin check causet t")
  2813  }
  2814  
  2815  func (s *testSuite) TestMilevaDBCurrentTS(c *C) {
  2816  	tk := testkit.NewTestKit(c, s.causetstore)
  2817  	tk.MustQuery("select @@milevadb_current_ts").Check(testkit.Rows("0"))
  2818  	tk.MustInterDirc("begin")
  2819  	rows := tk.MustQuery("select @@milevadb_current_ts").Rows()
  2820  	tsStr := rows[0][0].(string)
  2821  	txn, err := tk.Se.Txn(true)
  2822  	c.Assert(err, IsNil)
  2823  	c.Assert(tsStr, Equals, fmt.Sprintf("%d", txn.StartTS()))
  2824  	tk.MustInterDirc("begin")
  2825  	rows = tk.MustQuery("select @@milevadb_current_ts").Rows()
  2826  	newTsStr := rows[0][0].(string)
  2827  	txn, err = tk.Se.Txn(true)
  2828  	c.Assert(err, IsNil)
  2829  	c.Assert(newTsStr, Equals, fmt.Sprintf("%d", txn.StartTS()))
  2830  	c.Assert(newTsStr, Not(Equals), tsStr)
  2831  	tk.MustInterDirc("commit")
  2832  	tk.MustQuery("select @@milevadb_current_ts").Check(testkit.Rows("0"))
  2833  
  2834  	_, err = tk.InterDirc("set @@milevadb_current_ts = '1'")
  2835  	c.Assert(terror.ErrorEqual(err, variable.ErrReadOnly), IsTrue, Commentf("err %v", err))
  2836  }
  2837  
  2838  func (s *testSuite) TestMilevaDBLastTxnInfo(c *C) {
  2839  	tk := testkit.NewTestKit(c, s.causetstore)
  2840  	tk.MustInterDirc("use test")
  2841  	tk.MustInterDirc("drop causet if exists t")
  2842  	tk.MustInterDirc("create causet t (a int primary key)")
  2843  	tk.MustQuery("select json_extract(@@milevadb_last_txn_info, '$.start_ts'), json_extract(@@milevadb_last_txn_info, '$.commit_ts')").Check(testkit.Rows("0 0"))
  2844  
  2845  	tk.MustInterDirc("insert into t values (1)")
  2846  	rows1 := tk.MustQuery("select json_extract(@@milevadb_last_txn_info, '$.start_ts'), json_extract(@@milevadb_last_txn_info, '$.commit_ts')").Rows()
  2847  	c.Assert(rows1[0][0].(string), Greater, "0")
  2848  	c.Assert(rows1[0][0].(string), Less, rows1[0][1].(string))
  2849  
  2850  	tk.MustInterDirc("begin")
  2851  	tk.MustQuery("select a from t where a = 1").Check(testkit.Rows("1"))
  2852  	rows2 := tk.MustQuery("select json_extract(@@milevadb_last_txn_info, '$.start_ts'), json_extract(@@milevadb_last_txn_info, '$.commit_ts'), @@milevadb_current_ts").Rows()
  2853  	tk.MustInterDirc("commit")
  2854  	rows3 := tk.MustQuery("select json_extract(@@milevadb_last_txn_info, '$.start_ts'), json_extract(@@milevadb_last_txn_info, '$.commit_ts')").Rows()
  2855  	c.Assert(rows2[0][0], Equals, rows1[0][0])
  2856  	c.Assert(rows2[0][1], Equals, rows1[0][1])
  2857  	c.Assert(rows3[0][0], Equals, rows1[0][0])
  2858  	c.Assert(rows3[0][1], Equals, rows1[0][1])
  2859  	c.Assert(rows2[0][1], Less, rows2[0][2])
  2860  
  2861  	tk.MustInterDirc("begin")
  2862  	tk.MustInterDirc("uFIDelate t set a = a + 1 where a = 1")
  2863  	rows4 := tk.MustQuery("select json_extract(@@milevadb_last_txn_info, '$.start_ts'), json_extract(@@milevadb_last_txn_info, '$.commit_ts'), @@milevadb_current_ts").Rows()
  2864  	tk.MustInterDirc("commit")
  2865  	rows5 := tk.MustQuery("select json_extract(@@milevadb_last_txn_info, '$.start_ts'), json_extract(@@milevadb_last_txn_info, '$.commit_ts')").Rows()
  2866  	c.Assert(rows4[0][0], Equals, rows1[0][0])
  2867  	c.Assert(rows4[0][1], Equals, rows1[0][1])
  2868  	c.Assert(rows4[0][2], Equals, rows5[0][0])
  2869  	c.Assert(rows4[0][1], Less, rows4[0][2])
  2870  	c.Assert(rows4[0][2], Less, rows5[0][1])
  2871  
  2872  	tk.MustInterDirc("begin")
  2873  	tk.MustInterDirc("uFIDelate t set a = a + 1 where a = 2")
  2874  	tk.MustInterDirc("rollback")
  2875  	rows6 := tk.MustQuery("select json_extract(@@milevadb_last_txn_info, '$.start_ts'), json_extract(@@milevadb_last_txn_info, '$.commit_ts')").Rows()
  2876  	c.Assert(rows6[0][0], Equals, rows5[0][0])
  2877  	c.Assert(rows6[0][1], Equals, rows5[0][1])
  2878  
  2879  	tk.MustInterDirc("begin optimistic")
  2880  	tk.MustInterDirc("insert into t values (2)")
  2881  	_, err := tk.InterDirc("commit")
  2882  	c.Assert(err, NotNil)
  2883  	rows7 := tk.MustQuery("select json_extract(@@milevadb_last_txn_info, '$.start_ts'), json_extract(@@milevadb_last_txn_info, '$.commit_ts'), json_extract(@@milevadb_last_txn_info, '$.error')").Rows()
  2884  	c.Assert(rows7[0][0], Greater, rows5[0][0])
  2885  	c.Assert(rows7[0][1], Equals, "0")
  2886  	c.Assert(strings.Contains(err.Error(), rows7[0][1].(string)), IsTrue)
  2887  
  2888  	_, err = tk.InterDirc("set @@milevadb_last_txn_info = '{}'")
  2889  	c.Assert(terror.ErrorEqual(err, variable.ErrReadOnly), IsTrue, Commentf("err %v", err))
  2890  }
  2891  
  2892  func (s *testSuite) TestSelectForUFIDelate(c *C) {
  2893  	tk := testkit.NewTestKit(c, s.causetstore)
  2894  	tk.MustInterDirc("use test")
  2895  	tk1 := testkit.NewTestKit(c, s.causetstore)
  2896  	tk1.MustInterDirc("use test")
  2897  	tk2 := testkit.NewTestKit(c, s.causetstore)
  2898  	tk2.MustInterDirc("use test")
  2899  
  2900  	tk.MustInterDirc("drop causet if exists t, t1")
  2901  
  2902  	txn, err := tk.Se.Txn(true)
  2903  	c.Assert(ekv.ErrInvalidTxn.Equal(err), IsTrue)
  2904  	c.Assert(txn.Valid(), IsFalse)
  2905  	tk.MustInterDirc("create causet t (c1 int, c2 int, c3 int)")
  2906  	tk.MustInterDirc("insert t values (11, 2, 3)")
  2907  	tk.MustInterDirc("insert t values (12, 2, 3)")
  2908  	tk.MustInterDirc("insert t values (13, 2, 3)")
  2909  
  2910  	tk.MustInterDirc("create causet t1 (c1 int)")
  2911  	tk.MustInterDirc("insert t1 values (11)")
  2912  
  2913  	// conflict
  2914  	tk1.MustInterDirc("begin")
  2915  	tk1.MustQuery("select * from t where c1=11 for uFIDelate")
  2916  
  2917  	tk2.MustInterDirc("begin")
  2918  	tk2.MustInterDirc("uFIDelate t set c2=211 where c1=11")
  2919  	tk2.MustInterDirc("commit")
  2920  
  2921  	_, err = tk1.InterDirc("commit")
  2922  	c.Assert(err, NotNil)
  2923  
  2924  	// no conflict for subquery.
  2925  	tk1.MustInterDirc("begin")
  2926  	tk1.MustQuery("select * from t where exists(select null from t1 where t1.c1=t.c1) for uFIDelate")
  2927  
  2928  	tk2.MustInterDirc("begin")
  2929  	tk2.MustInterDirc("uFIDelate t set c2=211 where c1=12")
  2930  	tk2.MustInterDirc("commit")
  2931  
  2932  	tk1.MustInterDirc("commit")
  2933  
  2934  	// not conflict
  2935  	tk1.MustInterDirc("begin")
  2936  	tk1.MustQuery("select * from t where c1=11 for uFIDelate")
  2937  
  2938  	tk2.MustInterDirc("begin")
  2939  	tk2.MustInterDirc("uFIDelate t set c2=22 where c1=12")
  2940  	tk2.MustInterDirc("commit")
  2941  
  2942  	tk1.MustInterDirc("commit")
  2943  
  2944  	// not conflict, auto commit
  2945  	tk1.MustInterDirc("set @@autocommit=1;")
  2946  	tk1.MustQuery("select * from t where c1=11 for uFIDelate")
  2947  
  2948  	tk2.MustInterDirc("begin")
  2949  	tk2.MustInterDirc("uFIDelate t set c2=211 where c1=11")
  2950  	tk2.MustInterDirc("commit")
  2951  
  2952  	tk1.MustInterDirc("commit")
  2953  
  2954  	// conflict
  2955  	tk1.MustInterDirc("begin")
  2956  	tk1.MustQuery("select * from (select * from t for uFIDelate) t join t1 for uFIDelate")
  2957  
  2958  	tk2.MustInterDirc("begin")
  2959  	tk2.MustInterDirc("uFIDelate t1 set c1 = 13")
  2960  	tk2.MustInterDirc("commit")
  2961  
  2962  	_, err = tk1.InterDirc("commit")
  2963  	c.Assert(err, NotNil)
  2964  
  2965  }
  2966  
  2967  func (s *testSuite) TestEmptyEnum(c *C) {
  2968  	tk := testkit.NewTestKit(c, s.causetstore)
  2969  	tk.MustInterDirc("use test")
  2970  	tk.MustInterDirc("drop causet if exists t")
  2971  	tk.MustInterDirc("create causet t (e enum('Y', 'N'))")
  2972  	tk.MustInterDirc("set sql_mode='STRICT_TRANS_TABLES'")
  2973  	_, err := tk.InterDirc("insert into t values (0)")
  2974  	c.Assert(terror.ErrorEqual(err, types.ErrTruncated), IsTrue, Commentf("err %v", err))
  2975  	_, err = tk.InterDirc("insert into t values ('abc')")
  2976  	c.Assert(terror.ErrorEqual(err, types.ErrTruncated), IsTrue, Commentf("err %v", err))
  2977  
  2978  	tk.MustInterDirc("set sql_mode=''")
  2979  	tk.MustInterDirc("insert into t values (0)")
  2980  	tk.MustQuery("select * from t").Check(testkit.Rows(""))
  2981  	tk.MustInterDirc("insert into t values ('abc')")
  2982  	tk.MustQuery("select * from t").Check(testkit.Rows("", ""))
  2983  	tk.MustInterDirc("insert into t values (null)")
  2984  	tk.MustQuery("select * from t").Check(testkit.Rows("", "", "<nil>"))
  2985  }
  2986  
  2987  // TestIssue4024 This tests https://github.com/whtcorpsinc/milevadb/issues/4024
  2988  func (s *testSuite) TestIssue4024(c *C) {
  2989  	tk := testkit.NewTestKit(c, s.causetstore)
  2990  	tk.MustInterDirc("create database test2")
  2991  	tk.MustInterDirc("use test2")
  2992  	tk.MustInterDirc("create causet t(a int)")
  2993  	tk.MustInterDirc("insert into t values(1)")
  2994  	tk.MustInterDirc("use test")
  2995  	tk.MustInterDirc("create causet t(a int)")
  2996  	tk.MustInterDirc("insert into t values(1)")
  2997  	tk.MustInterDirc("uFIDelate t, test2.t set test2.t.a=2")
  2998  	tk.MustQuery("select * from t").Check(testkit.Rows("1"))
  2999  	tk.MustQuery("select * from test2.t").Check(testkit.Rows("2"))
  3000  	tk.MustInterDirc("uFIDelate test.t, test2.t set test.t.a=3")
  3001  	tk.MustQuery("select * from t").Check(testkit.Rows("3"))
  3002  	tk.MustQuery("select * from test2.t").Check(testkit.Rows("2"))
  3003  }
  3004  
  3005  const (
  3006  	checkRequestOff = iota
  3007  	checkRequestSyncLog
  3008  	checkDBSAddIndexPriority
  3009  )
  3010  
  3011  type checkRequestClient struct {
  3012  	einsteindb.Client
  3013  	priority       pb.CommandPri
  3014  	lowPriorityCnt uint32
  3015  	mu             struct {
  3016  		sync.RWMutex
  3017  		checkFlags uint32
  3018  		syncLog    bool
  3019  	}
  3020  }
  3021  
  3022  func (c *checkRequestClient) setCheckPriority(priority pb.CommandPri) {
  3023  	atomic.StoreInt32((*int32)(&c.priority), int32(priority))
  3024  }
  3025  
  3026  func (c *checkRequestClient) getCheckPriority() pb.CommandPri {
  3027  	return (pb.CommandPri)(atomic.LoadInt32((*int32)(&c.priority)))
  3028  }
  3029  
  3030  func (c *checkRequestClient) SendRequest(ctx context.Context, addr string, req *einsteindbrpc.Request, timeout time.Duration) (*einsteindbrpc.Response, error) {
  3031  	resp, err := c.Client.SendRequest(ctx, addr, req, timeout)
  3032  	c.mu.RLock()
  3033  	checkFlags := c.mu.checkFlags
  3034  	c.mu.RUnlock()
  3035  	if checkFlags == checkRequestSyncLog {
  3036  		switch req.Type {
  3037  		case einsteindbrpc.CmdPrewrite, einsteindbrpc.CmdCommit:
  3038  			c.mu.RLock()
  3039  			syncLog := c.mu.syncLog
  3040  			c.mu.RUnlock()
  3041  			if syncLog != req.SyncLog {
  3042  				return nil, errors.New("fail to set sync log")
  3043  			}
  3044  		}
  3045  	} else if checkFlags == checkDBSAddIndexPriority {
  3046  		if req.Type == einsteindbrpc.CmdScan {
  3047  			if c.getCheckPriority() != req.Priority {
  3048  				return nil, errors.New("fail to set priority")
  3049  			}
  3050  		} else if req.Type == einsteindbrpc.CmdPrewrite {
  3051  			if c.getCheckPriority() == pb.CommandPri_Low {
  3052  				atomic.AddUint32(&c.lowPriorityCnt, 1)
  3053  			}
  3054  		}
  3055  	}
  3056  	return resp, err
  3057  }
  3058  
  3059  type testSuiteWithCliBase struct {
  3060  	causetstore ekv.CausetStorage
  3061  	dom         *petri.Petri
  3062  	cli         *checkRequestClient
  3063  }
  3064  
  3065  type testSuite1 struct {
  3066  	testSuiteWithCliBase
  3067  }
  3068  
  3069  func (s *testSuiteWithCliBase) SetUpSuite(c *C) {
  3070  	cli := &checkRequestClient{}
  3071  	hijackClient := func(c einsteindb.Client) einsteindb.Client {
  3072  		cli.Client = c
  3073  		return cli
  3074  	}
  3075  	s.cli = cli
  3076  
  3077  	var err error
  3078  	s.causetstore, err = mockstore.NewMockStore(
  3079  		mockstore.WithClientHijacker(hijackClient),
  3080  	)
  3081  	c.Assert(err, IsNil)
  3082  	stochastik.SetStatsLease(0)
  3083  	s.dom, err = stochastik.BootstrapStochastik(s.causetstore)
  3084  	c.Assert(err, IsNil)
  3085  	s.dom.SetStatsUFIDelating(true)
  3086  }
  3087  
  3088  func (s *testSuiteWithCliBase) TearDownSuite(c *C) {
  3089  	s.dom.Close()
  3090  	s.causetstore.Close()
  3091  }
  3092  
  3093  func (s *testSuiteWithCliBase) TearDownTest(c *C) {
  3094  	tk := testkit.NewTestKit(c, s.causetstore)
  3095  	tk.MustInterDirc("use test")
  3096  	r := tk.MustQuery("show blocks")
  3097  	for _, tb := range r.Rows() {
  3098  		blockName := tb[0]
  3099  		tk.MustInterDirc(fmt.Sprintf("drop causet %v", blockName))
  3100  	}
  3101  }
  3102  
  3103  func (s *testSuite2) TestAddIndexPriority(c *C) {
  3104  	cli := &checkRequestClient{}
  3105  	hijackClient := func(c einsteindb.Client) einsteindb.Client {
  3106  		cli.Client = c
  3107  		return cli
  3108  	}
  3109  
  3110  	causetstore, err := mockstore.NewMockStore(
  3111  		mockstore.WithClientHijacker(hijackClient),
  3112  	)
  3113  	c.Assert(err, IsNil)
  3114  	dom, err := stochastik.BootstrapStochastik(causetstore)
  3115  	c.Assert(err, IsNil)
  3116  	defer func() {
  3117  		dom.Close()
  3118  		causetstore.Close()
  3119  	}()
  3120  
  3121  	tk := testkit.NewTestKit(c, causetstore)
  3122  	tk.MustInterDirc("use test")
  3123  	tk.MustInterDirc("create causet t1 (id int, v int)")
  3124  
  3125  	// Insert some data to make sure plan build IndexLookup for t1.
  3126  	for i := 0; i < 10; i++ {
  3127  		tk.MustInterDirc(fmt.Sprintf("insert into t1 values (%d, %d)", i, i))
  3128  	}
  3129  
  3130  	cli.mu.Lock()
  3131  	cli.mu.checkFlags = checkDBSAddIndexPriority
  3132  	cli.mu.Unlock()
  3133  
  3134  	cli.setCheckPriority(pb.CommandPri_Low)
  3135  	tk.MustInterDirc("alter causet t1 add index t1_index (id);")
  3136  
  3137  	c.Assert(atomic.LoadUint32(&cli.lowPriorityCnt) > 0, IsTrue)
  3138  
  3139  	cli.mu.Lock()
  3140  	cli.mu.checkFlags = checkRequestOff
  3141  	cli.mu.Unlock()
  3142  
  3143  	tk.MustInterDirc("alter causet t1 drop index t1_index;")
  3144  	tk.MustInterDirc("SET SESSION milevadb_dbs_reorg_priority = 'PRIORITY_NORMAL'")
  3145  
  3146  	cli.mu.Lock()
  3147  	cli.mu.checkFlags = checkDBSAddIndexPriority
  3148  	cli.mu.Unlock()
  3149  
  3150  	cli.setCheckPriority(pb.CommandPri_Normal)
  3151  	tk.MustInterDirc("alter causet t1 add index t1_index (id);")
  3152  
  3153  	cli.mu.Lock()
  3154  	cli.mu.checkFlags = checkRequestOff
  3155  	cli.mu.Unlock()
  3156  
  3157  	tk.MustInterDirc("alter causet t1 drop index t1_index;")
  3158  	tk.MustInterDirc("SET SESSION milevadb_dbs_reorg_priority = 'PRIORITY_HIGH'")
  3159  
  3160  	cli.mu.Lock()
  3161  	cli.mu.checkFlags = checkDBSAddIndexPriority
  3162  	cli.mu.Unlock()
  3163  
  3164  	cli.setCheckPriority(pb.CommandPri_High)
  3165  	tk.MustInterDirc("alter causet t1 add index t1_index (id);")
  3166  
  3167  	cli.mu.Lock()
  3168  	cli.mu.checkFlags = checkRequestOff
  3169  	cli.mu.Unlock()
  3170  }
  3171  
  3172  func (s *testSuite1) TestAlterBlockComment(c *C) {
  3173  	tk := testkit.NewTestKit(c, s.causetstore)
  3174  	tk.MustInterDirc("use test")
  3175  	tk.MustInterDirc("drop causet if exists t_1")
  3176  	tk.MustInterDirc("create causet t_1 (c1 int, c2 int, c3 int default 1, index (c1)) comment = 'test causet';")
  3177  	tk.MustInterDirc("alter causet `t_1` comment 'this is causet comment';")
  3178  	result := tk.MustQuery("select block_comment from information_schema.blocks where block_name = 't_1';")
  3179  	result.Check(testkit.Rows("this is causet comment"))
  3180  	tk.MustInterDirc("alter causet `t_1` comment 'causet t comment';")
  3181  	result = tk.MustQuery("select block_comment from information_schema.blocks where block_name = 't_1';")
  3182  	result.Check(testkit.Rows("causet t comment"))
  3183  }
  3184  
  3185  func (s *testSuite) TestTimezonePushDown(c *C) {
  3186  	tk := testkit.NewTestKit(c, s.causetstore)
  3187  	tk.MustInterDirc("use test")
  3188  	tk.MustInterDirc("create causet t (ts timestamp)")
  3189  	defer tk.MustInterDirc("drop causet t")
  3190  	tk.MustInterDirc(`insert into t values ("2020-09-13 10:02:06")`)
  3191  
  3192  	systemTZ := timeutil.SystemLocation()
  3193  	c.Assert(systemTZ.String(), Not(Equals), "System")
  3194  	c.Assert(systemTZ.String(), Not(Equals), "Local")
  3195  	ctx := context.Background()
  3196  	count := 0
  3197  	ctx1 := context.WithValue(ctx, "CheckSelectRequestHook", func(req *ekv.Request) {
  3198  		count += 1
  3199  		posetPosetDagReq := new(fidelpb.PosetDagRequest)
  3200  		err := proto.Unmarshal(req.Data, posetPosetDagReq)
  3201  		c.Assert(err, IsNil)
  3202  		c.Assert(posetPosetDagReq.GetTimeZoneName(), Equals, systemTZ.String())
  3203  	})
  3204  	tk.Se.InterDircute(ctx1, `select * from t where ts = "2020-09-13 10:02:06"`)
  3205  
  3206  	tk.MustInterDirc(`set time_zone="System"`)
  3207  	tk.Se.InterDircute(ctx1, `select * from t where ts = "2020-09-13 10:02:06"`)
  3208  
  3209  	c.Assert(count, Equals, 2) // Make sure the hook function is called.
  3210  }
  3211  
  3212  func (s *testSuite) TestNotFillCacheFlag(c *C) {
  3213  	tk := testkit.NewTestKit(c, s.causetstore)
  3214  	tk.MustInterDirc("use test")
  3215  	tk.MustInterDirc("create causet t (id int primary key)")
  3216  	defer tk.MustInterDirc("drop causet t")
  3217  	tk.MustInterDirc("insert into t values (1)")
  3218  
  3219  	tests := []struct {
  3220  		allegrosql string
  3221  		expect     bool
  3222  	}{
  3223  		{"select ALLEGROSQL_NO_CACHE * from t", true},
  3224  		{"select ALLEGROSQL_CACHE * from t", false},
  3225  		{"select * from t", false},
  3226  	}
  3227  	count := 0
  3228  	ctx := context.Background()
  3229  	for _, test := range tests {
  3230  		ctx1 := context.WithValue(ctx, "CheckSelectRequestHook", func(req *ekv.Request) {
  3231  			count++
  3232  			if req.NotFillCache != test.expect {
  3233  				c.Errorf("allegrosql=%s, expect=%v, get=%v", test.allegrosql, test.expect, req.NotFillCache)
  3234  			}
  3235  		})
  3236  		rs, err := tk.Se.InterDircute(ctx1, test.allegrosql)
  3237  		c.Assert(err, IsNil)
  3238  		tk.ResultSetToResult(rs[0], Commentf("allegrosql: %v", test.allegrosql))
  3239  	}
  3240  	c.Assert(count, Equals, len(tests)) // Make sure the hook function is called.
  3241  }
  3242  
  3243  func (s *testSuite1) TestSyncLog(c *C) {
  3244  	tk := testkit.NewTestKit(c, s.causetstore)
  3245  	tk.MustInterDirc("use test")
  3246  
  3247  	cli := s.cli
  3248  	cli.mu.Lock()
  3249  	cli.mu.checkFlags = checkRequestSyncLog
  3250  	cli.mu.syncLog = true
  3251  	cli.mu.Unlock()
  3252  	tk.MustInterDirc("create causet t (id int primary key)")
  3253  	cli.mu.Lock()
  3254  	cli.mu.syncLog = false
  3255  	cli.mu.Unlock()
  3256  	tk.MustInterDirc("insert into t values (1)")
  3257  
  3258  	cli.mu.Lock()
  3259  	cli.mu.checkFlags = checkRequestOff
  3260  	cli.mu.Unlock()
  3261  }
  3262  
  3263  func (s *testSuite) TestHandleTransfer(c *C) {
  3264  	tk := testkit.NewTestKit(c, s.causetstore)
  3265  	tk.MustInterDirc("use test")
  3266  	tk.MustInterDirc("create causet t(a int, index idx(a))")
  3267  	tk.MustInterDirc("insert into t values(1), (2), (4)")
  3268  	tk.MustInterDirc("begin")
  3269  	tk.MustInterDirc("uFIDelate t set a = 3 where a = 4")
  3270  	// test causet scan read whose result need handle.
  3271  	tk.MustQuery("select * from t ignore index(idx)").Check(testkit.Rows("1", "2", "3"))
  3272  	tk.MustInterDirc("insert into t values(4)")
  3273  	// test single read whose result need handle
  3274  	tk.MustQuery("select * from t use index(idx)").Check(testkit.Rows("1", "2", "3", "4"))
  3275  	tk.MustQuery("select * from t use index(idx) order by a desc").Check(testkit.Rows("4", "3", "2", "1"))
  3276  	tk.MustInterDirc("uFIDelate t set a = 5 where a = 3")
  3277  	tk.MustQuery("select * from t use index(idx)").Check(testkit.Rows("1", "2", "4", "5"))
  3278  	tk.MustInterDirc("commit")
  3279  
  3280  	tk.MustInterDirc("drop causet if exists t")
  3281  	tk.MustInterDirc("create causet t(a int, b int, index idx(a))")
  3282  	tk.MustInterDirc("insert into t values(3, 3), (1, 1), (2, 2)")
  3283  	// Second test double read.
  3284  	tk.MustQuery("select * from t use index(idx) order by a").Check(testkit.Rows("1 1", "2 2", "3 3"))
  3285  }
  3286  
  3287  func (s *testSuite) TestBit(c *C) {
  3288  	tk := testkit.NewTestKitWithInit(c, s.causetstore)
  3289  
  3290  	tk.MustInterDirc("drop causet if exists t")
  3291  	tk.MustInterDirc("create causet t (c1 bit(2))")
  3292  	tk.MustInterDirc("insert into t values (0), (1), (2), (3)")
  3293  	_, err := tk.InterDirc("insert into t values (4)")
  3294  	c.Assert(err, NotNil)
  3295  	_, err = tk.InterDirc("insert into t values ('a')")
  3296  	c.Assert(err, NotNil)
  3297  	r, err := tk.InterDirc("select * from t where c1 = 2")
  3298  	c.Assert(err, IsNil)
  3299  	req := r.NewChunk()
  3300  	err = r.Next(context.Background(), req)
  3301  	c.Assert(err, IsNil)
  3302  	c.Assert(types.BinaryLiteral(req.GetRow(0).GetBytes(0)), DeepEquals, types.NewBinaryLiteralFromUint(2, -1))
  3303  	r.Close()
  3304  
  3305  	tk.MustInterDirc("drop causet if exists t")
  3306  	tk.MustInterDirc("create causet t (c1 bit(31))")
  3307  	tk.MustInterDirc("insert into t values (0x7fffffff)")
  3308  	_, err = tk.InterDirc("insert into t values (0x80000000)")
  3309  	c.Assert(err, NotNil)
  3310  	_, err = tk.InterDirc("insert into t values (0xffffffff)")
  3311  	c.Assert(err, NotNil)
  3312  	tk.MustInterDirc("insert into t values ('123')")
  3313  	tk.MustInterDirc("insert into t values ('1234')")
  3314  	_, err = tk.InterDirc("insert into t values ('12345)")
  3315  	c.Assert(err, NotNil)
  3316  
  3317  	tk.MustInterDirc("drop causet if exists t")
  3318  	tk.MustInterDirc("create causet t (c1 bit(62))")
  3319  	tk.MustInterDirc("insert into t values ('12345678')")
  3320  	tk.MustInterDirc("drop causet if exists t")
  3321  	tk.MustInterDirc("create causet t (c1 bit(61))")
  3322  	_, err = tk.InterDirc("insert into t values ('12345678')")
  3323  	c.Assert(err, NotNil)
  3324  
  3325  	tk.MustInterDirc("drop causet if exists t")
  3326  	tk.MustInterDirc("create causet t (c1 bit(32))")
  3327  	tk.MustInterDirc("insert into t values (0x7fffffff)")
  3328  	tk.MustInterDirc("insert into t values (0xffffffff)")
  3329  	_, err = tk.InterDirc("insert into t values (0x1ffffffff)")
  3330  	c.Assert(err, NotNil)
  3331  	tk.MustInterDirc("insert into t values ('1234')")
  3332  	_, err = tk.InterDirc("insert into t values ('12345')")
  3333  	c.Assert(err, NotNil)
  3334  
  3335  	tk.MustInterDirc("drop causet if exists t")
  3336  	tk.MustInterDirc("create causet t (c1 bit(64))")
  3337  	tk.MustInterDirc("insert into t values (0xffffffffffffffff)")
  3338  	tk.MustInterDirc("insert into t values ('12345678')")
  3339  	_, err = tk.InterDirc("insert into t values ('123456789')")
  3340  	c.Assert(err, NotNil)
  3341  }
  3342  
  3343  func (s *testSuite) TestEnum(c *C) {
  3344  	tk := testkit.NewTestKitWithInit(c, s.causetstore)
  3345  
  3346  	tk.MustInterDirc("drop causet if exists t")
  3347  	tk.MustInterDirc("create causet t (c enum('a', 'b', 'c'))")
  3348  	tk.MustInterDirc("insert into t values ('a'), (2), ('c')")
  3349  	tk.MustQuery("select * from t where c = 'a'").Check(testkit.Rows("a"))
  3350  
  3351  	tk.MustQuery("select c + 1 from t where c = 2").Check(testkit.Rows("3"))
  3352  
  3353  	tk.MustInterDirc("delete from t")
  3354  	tk.MustInterDirc("insert into t values ()")
  3355  	tk.MustInterDirc("insert into t values (null), ('1')")
  3356  	tk.MustQuery("select c + 1 from t where c = 1").Check(testkit.Rows("2"))
  3357  }
  3358  
  3359  func (s *testSuite) TestSet(c *C) {
  3360  	tk := testkit.NewTestKitWithInit(c, s.causetstore)
  3361  
  3362  	tk.MustInterDirc("drop causet if exists t")
  3363  	tk.MustInterDirc("create causet t (c set('a', 'b', 'c'))")
  3364  	tk.MustInterDirc("insert into t values ('a'), (2), ('c'), ('a,b'), ('b,a')")
  3365  	tk.MustQuery("select * from t where c = 'a'").Check(testkit.Rows("a"))
  3366  
  3367  	tk.MustQuery("select * from t where c = 'a,b'").Check(testkit.Rows("a,b", "a,b"))
  3368  
  3369  	tk.MustQuery("select c + 1 from t where c = 2").Check(testkit.Rows("3"))
  3370  
  3371  	tk.MustInterDirc("delete from t")
  3372  	tk.MustInterDirc("insert into t values ()")
  3373  	tk.MustInterDirc("insert into t values (null), ('1')")
  3374  	tk.MustQuery("select c + 1 from t where c = 1").Check(testkit.Rows("2"))
  3375  }
  3376  
  3377  func (s *testSuite) TestSubqueryInValues(c *C) {
  3378  	tk := testkit.NewTestKitWithInit(c, s.causetstore)
  3379  
  3380  	tk.MustInterDirc("drop causet if exists t")
  3381  	tk.MustInterDirc("create causet t (id int, name varchar(20))")
  3382  	tk.MustInterDirc("drop causet if exists t1")
  3383  	tk.MustInterDirc("create causet t1 (gid int)")
  3384  
  3385  	tk.MustInterDirc("insert into t1 (gid) value (1)")
  3386  	tk.MustInterDirc("insert into t (id, name) value ((select gid from t1) ,'asd')")
  3387  	tk.MustQuery("select * from t").Check(testkit.Rows("1 asd"))
  3388  }
  3389  
  3390  func (s *testSuite) TestEnhancedRangeAccess(c *C) {
  3391  	tk := testkit.NewTestKitWithInit(c, s.causetstore)
  3392  
  3393  	tk.MustInterDirc("drop causet if exists t")
  3394  	tk.MustInterDirc("create causet t (a int primary key, b int)")
  3395  	tk.MustInterDirc("insert into t values(1, 2), (2, 1)")
  3396  	tk.MustQuery("select * from t where (a = 1 and b = 2) or (a = 2 and b = 1)").Check(testkit.Rows("1 2", "2 1"))
  3397  	tk.MustQuery("select * from t where (a = 1 and b = 1) or (a = 2 and b = 2)").Check(nil)
  3398  }
  3399  
  3400  // TestMaxInt64Handle Issue #4810
  3401  func (s *testSuite) TestMaxInt64Handle(c *C) {
  3402  	tk := testkit.NewTestKitWithInit(c, s.causetstore)
  3403  
  3404  	tk.MustInterDirc("drop causet if exists t")
  3405  	tk.MustInterDirc("create causet t(id bigint, PRIMARY KEY (id))")
  3406  	tk.MustInterDirc("insert into t values(9223372036854775807)")
  3407  	tk.MustInterDirc("select * from t where id = 9223372036854775807")
  3408  	tk.MustQuery("select * from t where id = 9223372036854775807;").Check(testkit.Rows("9223372036854775807"))
  3409  	tk.MustQuery("select * from t").Check(testkit.Rows("9223372036854775807"))
  3410  	_, err := tk.InterDirc("insert into t values(9223372036854775807)")
  3411  	c.Assert(err, NotNil)
  3412  	tk.MustInterDirc("delete from t where id = 9223372036854775807")
  3413  	tk.MustQuery("select * from t").Check(nil)
  3414  }
  3415  
  3416  func (s *testSuite) TestBlockScanWithPointRanges(c *C) {
  3417  	tk := testkit.NewTestKitWithInit(c, s.causetstore)
  3418  
  3419  	tk.MustInterDirc("drop causet if exists t")
  3420  	tk.MustInterDirc("create causet t(id int, PRIMARY KEY (id))")
  3421  	tk.MustInterDirc("insert into t values(1), (5), (10)")
  3422  	tk.MustQuery("select * from t where id in(1, 2, 10)").Check(testkit.Rows("1", "10"))
  3423  }
  3424  
  3425  func (s *testSuite) TestUnsignedPk(c *C) {
  3426  	tk := testkit.NewTestKitWithInit(c, s.causetstore)
  3427  
  3428  	tk.MustInterDirc("drop causet if exists t")
  3429  	tk.MustInterDirc("create causet t(id bigint unsigned primary key)")
  3430  	var num1, num2 uint64 = math.MaxInt64 + 1, math.MaxInt64 + 2
  3431  	tk.MustInterDirc(fmt.Sprintf("insert into t values(%v), (%v), (1), (2)", num1, num2))
  3432  	num1Str := strconv.FormatUint(num1, 10)
  3433  	num2Str := strconv.FormatUint(num2, 10)
  3434  	tk.MustQuery("select * from t order by id").Check(testkit.Rows("1", "2", num1Str, num2Str))
  3435  	tk.MustQuery("select * from t where id not in (2)").Check(testkit.Rows(num1Str, num2Str, "1"))
  3436  	tk.MustInterDirc("drop causet t")
  3437  	tk.MustInterDirc("create causet t(a bigint unsigned primary key, b int, index idx(b))")
  3438  	tk.MustInterDirc("insert into t values(9223372036854775808, 1), (1, 1)")
  3439  	tk.MustQuery("select * from t use index(idx) where b = 1 and a < 2").Check(testkit.Rows("1 1"))
  3440  	tk.MustQuery("select * from t use index(idx) where b = 1 order by b, a").Check(testkit.Rows("1 1", "9223372036854775808 1"))
  3441  }
  3442  
  3443  func (s *testSuite) TestIssue5666(c *C) {
  3444  	tk := testkit.NewTestKit(c, s.causetstore)
  3445  	tk.MustInterDirc("set @@profiling=1")
  3446  	tk.MustQuery("SELECT QUERY_ID, SUM(DURATION) AS SUM_DURATION FROM INFORMATION_SCHEMA.PROFILING GROUP BY QUERY_ID;").Check(testkit.Rows("0 0"))
  3447  }
  3448  
  3449  func (s *testSuite) TestIssue5341(c *C) {
  3450  	tk := testkit.NewTestKit(c, s.causetstore)
  3451  	tk.MustInterDirc("drop causet if exists test.t")
  3452  	tk.MustInterDirc("create causet test.t(a char)")
  3453  	tk.MustInterDirc("insert into test.t value('a')")
  3454  	tk.MustQuery("select * from test.t where a < 1 order by a limit 0;").Check(testkit.Rows())
  3455  }
  3456  
  3457  func (s *testSuite) TestContainDotDeferredCauset(c *C) {
  3458  	tk := testkit.NewTestKit(c, s.causetstore)
  3459  
  3460  	tk.MustInterDirc("use test")
  3461  	tk.MustInterDirc("drop causet if exists test.t1")
  3462  	tk.MustInterDirc("create causet test.t1(t1.a char)")
  3463  	tk.MustInterDirc("drop causet if exists t2")
  3464  	tk.MustInterDirc("create causet t2(a char, t2.b int)")
  3465  
  3466  	tk.MustInterDirc("drop causet if exists t3")
  3467  	_, err := tk.InterDirc("create causet t3(s.a char);")
  3468  	terr := errors.Cause(err).(*terror.Error)
  3469  	c.Assert(terr.Code(), Equals, errors.ErrCode(allegrosql.ErrWrongBlockName))
  3470  }
  3471  
  3472  func (s *testSuite) TestChecHoTTex(c *C) {
  3473  	s.ctx = mock.NewContext()
  3474  	s.ctx.CausetStore = s.causetstore
  3475  	se, err := stochastik.CreateStochastik4Test(s.causetstore)
  3476  	c.Assert(err, IsNil)
  3477  	defer se.Close()
  3478  
  3479  	_, err = se.InterDircute(context.Background(), "create database test_admin")
  3480  	c.Assert(err, IsNil)
  3481  	_, err = se.InterDircute(context.Background(), "use test_admin")
  3482  	c.Assert(err, IsNil)
  3483  	_, err = se.InterDircute(context.Background(), "create causet t (pk int primary key, c int default 1, c1 int default 1, unique key c(c))")
  3484  	c.Assert(err, IsNil)
  3485  	is := s.petri.SchemaReplicant()
  3486  	EDB := perceptron.NewCIStr("test_admin")
  3487  	dbInfo, ok := is.SchemaByName(EDB)
  3488  	c.Assert(ok, IsTrue)
  3489  	tblName := perceptron.NewCIStr("t")
  3490  	tbl, err := is.BlockByName(EDB, tblName)
  3491  	c.Assert(err, IsNil)
  3492  	tbInfo := tbl.Meta()
  3493  
  3494  	alloc := autoid.NewSlabPredictor(s.causetstore, dbInfo.ID, false, autoid.RowIDAllocType)
  3495  	tb, err := blocks.BlockFromMeta(autoid.NewSlabPredictors(alloc), tbInfo)
  3496  	c.Assert(err, IsNil)
  3497  
  3498  	_, err = se.InterDircute(context.Background(), "admin check index t c")
  3499  	c.Assert(err, IsNil)
  3500  
  3501  	_, err = se.InterDircute(context.Background(), "admin check index t C")
  3502  	c.Assert(err, IsNil)
  3503  
  3504  	// set data to:
  3505  	// index     data (handle, data): (1, 10), (2, 20)
  3506  	// causet     data (handle, data): (1, 10), (2, 20)
  3507  	recordVal1 := types.MakeCausets(int64(1), int64(10), int64(11))
  3508  	recordVal2 := types.MakeCausets(int64(2), int64(20), int64(21))
  3509  	c.Assert(s.ctx.NewTxn(context.Background()), IsNil)
  3510  	_, err = tb.AddRecord(s.ctx, recordVal1)
  3511  	c.Assert(err, IsNil)
  3512  	_, err = tb.AddRecord(s.ctx, recordVal2)
  3513  	c.Assert(err, IsNil)
  3514  	txn, err := s.ctx.Txn(true)
  3515  	c.Assert(err, IsNil)
  3516  	c.Assert(txn.Commit(context.Background()), IsNil)
  3517  
  3518  	mockCtx := mock.NewContext()
  3519  	idx := tb.Indices()[0]
  3520  	sc := &stmtctx.StatementContext{TimeZone: time.Local}
  3521  
  3522  	_, err = se.InterDircute(context.Background(), "admin check index t idx_inexistent")
  3523  	c.Assert(strings.Contains(err.Error(), "not exist"), IsTrue)
  3524  
  3525  	// set data to:
  3526  	// index     data (handle, data): (1, 10), (2, 20), (3, 30)
  3527  	// causet     data (handle, data): (1, 10), (2, 20), (4, 40)
  3528  	txn, err = s.causetstore.Begin()
  3529  	c.Assert(err, IsNil)
  3530  	_, err = idx.Create(mockCtx, txn.GetUnionStore(), types.MakeCausets(int64(30)), ekv.IntHandle(3))
  3531  	c.Assert(err, IsNil)
  3532  	key := blockcodec.EncodeRowKey(tb.Meta().ID, ekv.IntHandle(4).Encoded())
  3533  	setDefCausValue(c, txn, key, types.NewCauset(int64(40)))
  3534  	err = txn.Commit(context.Background())
  3535  	c.Assert(err, IsNil)
  3536  	_, err = se.InterDircute(context.Background(), "admin check index t c")
  3537  	c.Assert(err, NotNil)
  3538  	c.Assert(err.Error(), Equals, "handle 3, index:types.Causet{k:0x1, decimal:0x0, length:0x0, i:30, defCauslation:\"\", b:[]uint8(nil), x:interface {}(nil)} != record:<nil>")
  3539  
  3540  	// set data to:
  3541  	// index     data (handle, data): (1, 10), (2, 20), (3, 30), (4, 40)
  3542  	// causet     data (handle, data): (1, 10), (2, 20), (4, 40)
  3543  	txn, err = s.causetstore.Begin()
  3544  	c.Assert(err, IsNil)
  3545  	_, err = idx.Create(mockCtx, txn.GetUnionStore(), types.MakeCausets(int64(40)), ekv.IntHandle(4))
  3546  	c.Assert(err, IsNil)
  3547  	err = txn.Commit(context.Background())
  3548  	c.Assert(err, IsNil)
  3549  	_, err = se.InterDircute(context.Background(), "admin check index t c")
  3550  	c.Assert(strings.Contains(err.Error(), "causet count 3 != index(c) count 4"), IsTrue)
  3551  
  3552  	// set data to:
  3553  	// index     data (handle, data): (1, 10), (4, 40)
  3554  	// causet     data (handle, data): (1, 10), (2, 20), (4, 40)
  3555  	txn, err = s.causetstore.Begin()
  3556  	c.Assert(err, IsNil)
  3557  	err = idx.Delete(sc, txn, types.MakeCausets(int64(30)), ekv.IntHandle(3))
  3558  	c.Assert(err, IsNil)
  3559  	err = idx.Delete(sc, txn, types.MakeCausets(int64(20)), ekv.IntHandle(2))
  3560  	c.Assert(err, IsNil)
  3561  	err = txn.Commit(context.Background())
  3562  	c.Assert(err, IsNil)
  3563  	_, err = se.InterDircute(context.Background(), "admin check index t c")
  3564  	c.Assert(strings.Contains(err.Error(), "causet count 3 != index(c) count 2"), IsTrue)
  3565  
  3566  	// TODO: pass the case below:
  3567  	// set data to:
  3568  	// index     data (handle, data): (1, 10), (4, 40), (2, 30)
  3569  	// causet     data (handle, data): (1, 10), (2, 20), (4, 40)
  3570  }
  3571  
  3572  func setDefCausValue(c *C, txn ekv.Transaction, key ekv.Key, v types.Causet) {
  3573  	event := []types.Causet{v, {}}
  3574  	defCausIDs := []int64{2, 3}
  3575  	sc := &stmtctx.StatementContext{TimeZone: time.Local}
  3576  	rd := rowcodec.CausetEncoder{Enable: true}
  3577  	value, err := blockcodec.EncodeRow(sc, event, defCausIDs, nil, nil, &rd)
  3578  	c.Assert(err, IsNil)
  3579  	err = txn.Set(key, value)
  3580  	c.Assert(err, IsNil)
  3581  }
  3582  
  3583  func (s *testSuite) TestCheckBlock(c *C) {
  3584  	tk := testkit.NewTestKit(c, s.causetstore)
  3585  
  3586  	// Test 'admin check causet' when the causet has a unique index with null values.
  3587  	tk.MustInterDirc("use test")
  3588  	tk.MustInterDirc("drop causet if exists admin_test;")
  3589  	tk.MustInterDirc("create causet admin_test (c1 int, c2 int, c3 int default 1, index (c1), unique key(c2));")
  3590  	tk.MustInterDirc("insert admin_test (c1, c2) values (1, 1), (2, 2), (NULL, NULL);")
  3591  	tk.MustInterDirc("admin check causet admin_test;")
  3592  }
  3593  
  3594  func (s *testSuite) TestCheckBlockClusterIndex(c *C) {
  3595  	tk := testkit.NewTestKit(c, s.causetstore)
  3596  
  3597  	tk.MustInterDirc("use test;")
  3598  	tk.MustInterDirc("set @@milevadb_enable_clustered_index = 1;")
  3599  	tk.MustInterDirc("drop causet if exists admin_test;")
  3600  	tk.MustInterDirc("create causet admin_test (c1 int, c2 int, c3 int default 1, primary key (c1, c2), index (c1), unique key(c2));")
  3601  	tk.MustInterDirc("insert admin_test (c1, c2) values (1, 1), (2, 2), (3, 3);")
  3602  	tk.MustInterDirc("admin check causet admin_test;")
  3603  }
  3604  
  3605  func (s *testSuite) TestCoprocessorStreamingFlag(c *C) {
  3606  	tk := testkit.NewTestKit(c, s.causetstore)
  3607  
  3608  	tk.MustInterDirc("use test")
  3609  	tk.MustInterDirc("create causet t (id int, value int, index idx(id))")
  3610  	// Add some data to make statistics work.
  3611  	for i := 0; i < 100; i++ {
  3612  		tk.MustInterDirc(fmt.Sprintf("insert into t values (%d, %d)", i, i))
  3613  	}
  3614  
  3615  	tests := []struct {
  3616  		allegrosql string
  3617  		expect     bool
  3618  	}{
  3619  		{"select * from t", true},                         // BlockReader
  3620  		{"select * from t where id = 5", true},            // IndexLookup
  3621  		{"select * from t where id > 5", true},            // Filter
  3622  		{"select * from t limit 3", false},                // Limit
  3623  		{"select avg(id) from t", false},                  // Aggregate
  3624  		{"select * from t order by value limit 3", false}, // TopN
  3625  	}
  3626  
  3627  	ctx := context.Background()
  3628  	for _, test := range tests {
  3629  		ctx1 := context.WithValue(ctx, "CheckSelectRequestHook", func(req *ekv.Request) {
  3630  			if req.Streaming != test.expect {
  3631  				c.Errorf("allegrosql=%s, expect=%v, get=%v", test.allegrosql, test.expect, req.Streaming)
  3632  			}
  3633  		})
  3634  		rs, err := tk.Se.InterDircute(ctx1, test.allegrosql)
  3635  		c.Assert(err, IsNil)
  3636  		tk.ResultSetToResult(rs[0], Commentf("allegrosql: %v", test.allegrosql))
  3637  	}
  3638  }
  3639  
  3640  func (s *testSuite) TestIncorrectLimitArg(c *C) {
  3641  	tk := testkit.NewTestKit(c, s.causetstore)
  3642  
  3643  	tk.MustInterDirc(`use test;`)
  3644  	tk.MustInterDirc(`drop causet if exists t;`)
  3645  	tk.MustInterDirc(`create causet t(a bigint);`)
  3646  	tk.MustInterDirc(`prepare stmt1 from 'select * from t limit ?';`)
  3647  	tk.MustInterDirc(`prepare stmt2 from 'select * from t limit ?, ?';`)
  3648  	tk.MustInterDirc(`set @a = -1;`)
  3649  	tk.MustInterDirc(`set @b =  1;`)
  3650  
  3651  	var err error
  3652  	_, err = tk.Se.InterDircute(context.TODO(), `execute stmt1 using @a;`)
  3653  	c.Assert(err.Error(), Equals, `[causet:1210]Incorrect arguments to LIMIT`)
  3654  
  3655  	_, err = tk.Se.InterDircute(context.TODO(), `execute stmt2 using @b, @a;`)
  3656  	c.Assert(err.Error(), Equals, `[causet:1210]Incorrect arguments to LIMIT`)
  3657  }
  3658  
  3659  func (s *testSuite) TestLimit(c *C) {
  3660  	tk := testkit.NewTestKit(c, s.causetstore)
  3661  	tk.MustInterDirc(`use test;`)
  3662  	tk.MustInterDirc(`drop causet if exists t;`)
  3663  	tk.MustInterDirc(`create causet t(a bigint, b bigint);`)
  3664  	tk.MustInterDirc(`insert into t values(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6);`)
  3665  	tk.MustQuery(`select * from t order by a limit 1, 1;`).Check(testkit.Rows(
  3666  		"2 2",
  3667  	))
  3668  	tk.MustQuery(`select * from t order by a limit 1, 2;`).Check(testkit.Rows(
  3669  		"2 2",
  3670  		"3 3",
  3671  	))
  3672  	tk.MustQuery(`select * from t order by a limit 1, 3;`).Check(testkit.Rows(
  3673  		"2 2",
  3674  		"3 3",
  3675  		"4 4",
  3676  	))
  3677  	tk.MustQuery(`select * from t order by a limit 1, 4;`).Check(testkit.Rows(
  3678  		"2 2",
  3679  		"3 3",
  3680  		"4 4",
  3681  		"5 5",
  3682  	))
  3683  	tk.MustInterDirc(`set @@milevadb_init_chunk_size=2;`)
  3684  	tk.MustQuery(`select * from t order by a limit 2, 1;`).Check(testkit.Rows(
  3685  		"3 3",
  3686  	))
  3687  	tk.MustQuery(`select * from t order by a limit 2, 2;`).Check(testkit.Rows(
  3688  		"3 3",
  3689  		"4 4",
  3690  	))
  3691  	tk.MustQuery(`select * from t order by a limit 2, 3;`).Check(testkit.Rows(
  3692  		"3 3",
  3693  		"4 4",
  3694  		"5 5",
  3695  	))
  3696  	tk.MustQuery(`select * from t order by a limit 2, 4;`).Check(testkit.Rows(
  3697  		"3 3",
  3698  		"4 4",
  3699  		"5 5",
  3700  		"6 6",
  3701  	))
  3702  }
  3703  
  3704  func (s *testSuite) TestCoprocessorStreamingWarning(c *C) {
  3705  	tk := testkit.NewTestKit(c, s.causetstore)
  3706  	tk.MustInterDirc("use test")
  3707  	tk.MustInterDirc("drop causet if exists t")
  3708  	tk.MustInterDirc("create causet t(a double)")
  3709  	tk.MustInterDirc("insert into t value(1.2)")
  3710  	tk.MustInterDirc("set @@stochastik.milevadb_enable_streaming = 1")
  3711  
  3712  	result := tk.MustQuery("select * from t where a/0 > 1")
  3713  	result.Check(testkit.Rows())
  3714  	tk.MustQuery("show warnings").Check(solitonutil.RowsWithSep("|", "Warning|1365|Division by 0"))
  3715  }
  3716  
  3717  func (s *testSuite3) TestYearTypeDeleteIndex(c *C) {
  3718  	tk := testkit.NewTestKit(c, s.causetstore)
  3719  	tk.MustInterDirc("use test")
  3720  	tk.MustInterDirc("drop causet if exists t")
  3721  	tk.MustInterDirc("create causet t(a YEAR, PRIMARY KEY(a));")
  3722  	tk.MustInterDirc("insert into t set a = '2151';")
  3723  	tk.MustInterDirc("delete from t;")
  3724  	tk.MustInterDirc("admin check causet t")
  3725  }
  3726  
  3727  func (s *testSuite3) TestForSelectScopeInUnion(c *C) {
  3728  	// A union B for uFIDelate, the "for uFIDelate" option belongs to union memex, so
  3729  	// it should works on both A and B.
  3730  	tk1 := testkit.NewTestKit(c, s.causetstore)
  3731  	tk2 := testkit.NewTestKit(c, s.causetstore)
  3732  	tk1.MustInterDirc("use test")
  3733  	tk1.MustInterDirc("drop causet if exists t")
  3734  	tk1.MustInterDirc("create causet t(a int)")
  3735  	tk1.MustInterDirc("insert into t values (1)")
  3736  
  3737  	tk1.MustInterDirc("begin")
  3738  	// 'For uFIDelate' would act on the second select.
  3739  	tk1.MustQuery("select 1 as a union select a from t for uFIDelate")
  3740  
  3741  	tk2.MustInterDirc("use test")
  3742  	tk2.MustInterDirc("uFIDelate t set a = a + 1")
  3743  
  3744  	// As tk1 use select 'for uFIDelate', it should detect conflict and fail.
  3745  	_, err := tk1.InterDirc("commit")
  3746  	c.Assert(err, NotNil)
  3747  
  3748  	tk1.MustInterDirc("begin")
  3749  	// 'For uFIDelate' would be ignored if 'order by' or 'limit' exists.
  3750  	tk1.MustQuery("select 1 as a union select a from t limit 5 for uFIDelate")
  3751  	tk1.MustQuery("select 1 as a union select a from t order by a for uFIDelate")
  3752  
  3753  	tk2.MustInterDirc("uFIDelate t set a = a + 1")
  3754  
  3755  	_, err = tk1.InterDirc("commit")
  3756  	c.Assert(err, IsNil)
  3757  }
  3758  
  3759  func (s *testSuite3) TestUnsignedDecimalOverflow(c *C) {
  3760  	tests := []struct {
  3761  		input  interface{}
  3762  		hasErr bool
  3763  		err    string
  3764  	}{{
  3765  		-1,
  3766  		true,
  3767  		"Out of range value for defCausumn",
  3768  	}, {
  3769  		"-1.1e-1",
  3770  		true,
  3771  		"Out of range value for defCausumn",
  3772  	}, {
  3773  		-1.1,
  3774  		true,
  3775  		"Out of range value for defCausumn",
  3776  	}, {
  3777  		-0,
  3778  		false,
  3779  		"",
  3780  	},
  3781  	}
  3782  	tk := testkit.NewTestKit(c, s.causetstore)
  3783  	tk.MustInterDirc("use test")
  3784  	tk.MustInterDirc("drop causet if exists t")
  3785  	tk.MustInterDirc("create causet t(a decimal(10,2) unsigned)")
  3786  	for _, t := range tests {
  3787  		res, err := tk.InterDirc("insert into t values (?)", t.input)
  3788  		if res != nil {
  3789  			defer res.Close()
  3790  		}
  3791  		if t.hasErr {
  3792  			c.Assert(err, NotNil)
  3793  			c.Assert(strings.Contains(err.Error(), t.err), IsTrue)
  3794  		} else {
  3795  			c.Assert(err, IsNil)
  3796  		}
  3797  		if res != nil {
  3798  			res.Close()
  3799  		}
  3800  	}
  3801  
  3802  	tk.MustInterDirc("set sql_mode=''")
  3803  	tk.MustInterDirc("delete from t")
  3804  	tk.MustInterDirc("insert into t values (?)", -1)
  3805  	r := tk.MustQuery("select a from t limit 1")
  3806  	r.Check(testkit.Rows("0.00"))
  3807  }
  3808  
  3809  func (s *testSuite3) TestIndexJoinBlockDualPanic(c *C) {
  3810  	tk := testkit.NewTestKit(c, s.causetstore)
  3811  	tk.MustInterDirc("use test")
  3812  	tk.MustInterDirc("drop causet if exists a")
  3813  	tk.MustInterDirc("create causet a (f1 int, f2 varchar(32), primary key (f1))")
  3814  	tk.MustInterDirc("insert into a (f1,f2) values (1,'a'), (2,'b'), (3,'c')")
  3815  	tk.MustQuery("select a.* from a inner join (select 1 as k1,'k2-1' as k2) as k on a.f1=k.k1;").
  3816  		Check(testkit.Rows("1 a"))
  3817  }
  3818  
  3819  func (s *testSuite3) TestSortLeftJoinWithNullDeferredCausetInRightChildPanic(c *C) {
  3820  	tk := testkit.NewTestKit(c, s.causetstore)
  3821  	tk.MustInterDirc("use test")
  3822  	tk.MustInterDirc("drop causet if exists t1, t2")
  3823  	tk.MustInterDirc("create causet t1(a int)")
  3824  	tk.MustInterDirc("create causet t2(a int)")
  3825  	tk.MustInterDirc("insert into t1(a) select 1;")
  3826  	tk.MustQuery("select b.n from t1 left join (select a as a, null as n from t2) b on b.a = t1.a order by t1.a").
  3827  		Check(testkit.Rows("<nil>"))
  3828  }
  3829  
  3830  func (s *testSuiteP1) TestUnionAutoSignedCast(c *C) {
  3831  	tk := testkit.NewTestKit(c, s.causetstore)
  3832  	tk.MustInterDirc("use test")
  3833  	tk.MustInterDirc("drop causet if exists t1,t2")
  3834  	tk.MustInterDirc("create causet t1 (id int, i int, b bigint, d double, dd decimal)")
  3835  	tk.MustInterDirc("create causet t2 (id int, i int unsigned, b bigint unsigned, d double unsigned, dd decimal unsigned)")
  3836  	tk.MustInterDirc("insert into t1 values(1, -1, -1, -1.1, -1)")
  3837  	tk.MustInterDirc("insert into t2 values(2, 1, 1, 1.1, 1)")
  3838  	tk.MustQuery("select * from t1 union select * from t2 order by id").
  3839  		Check(testkit.Rows("1 -1 -1 -1.1 -1", "2 1 1 1.1 1"))
  3840  	tk.MustQuery("select id, i, b, d, dd from t2 union select id, i, b, d, dd from t1 order by id").
  3841  		Check(testkit.Rows("1 0 0 0 -1", "2 1 1 1.1 1"))
  3842  	tk.MustQuery("select id, i from t2 union select id, cast(i as unsigned int) from t1 order by id").
  3843  		Check(testkit.Rows("1 18446744073709551615", "2 1"))
  3844  	tk.MustQuery("select dd from t2 union all select dd from t2").
  3845  		Check(testkit.Rows("1", "1"))
  3846  
  3847  	tk.MustInterDirc("drop causet if exists t3,t4")
  3848  	tk.MustInterDirc("create causet t3 (id int, v int)")
  3849  	tk.MustInterDirc("create causet t4 (id int, v double unsigned)")
  3850  	tk.MustInterDirc("insert into t3 values (1, -1)")
  3851  	tk.MustInterDirc("insert into t4 values (2, 1)")
  3852  	tk.MustQuery("select id, v from t3 union select id, v from t4 order by id").
  3853  		Check(testkit.Rows("1 -1", "2 1"))
  3854  	tk.MustQuery("select id, v from t4 union select id, v from t3 order by id").
  3855  		Check(testkit.Rows("1 0", "2 1"))
  3856  
  3857  	tk.MustInterDirc("drop causet if exists t5,t6,t7")
  3858  	tk.MustInterDirc("create causet t5 (id int, v bigint unsigned)")
  3859  	tk.MustInterDirc("create causet t6 (id int, v decimal)")
  3860  	tk.MustInterDirc("create causet t7 (id int, v bigint)")
  3861  	tk.MustInterDirc("insert into t5 values (1, 1)")
  3862  	tk.MustInterDirc("insert into t6 values (2, -1)")
  3863  	tk.MustInterDirc("insert into t7 values (3, -1)")
  3864  	tk.MustQuery("select id, v from t5 union select id, v from t6 order by id").
  3865  		Check(testkit.Rows("1 1", "2 -1"))
  3866  	tk.MustQuery("select id, v from t5 union select id, v from t7 union select id, v from t6 order by id").
  3867  		Check(testkit.Rows("1 1", "2 -1", "3 -1"))
  3868  }
  3869  
  3870  func (s *testSuite6) TestUFIDelateJoin(c *C) {
  3871  	tk := testkit.NewTestKit(c, s.causetstore)
  3872  	tk.MustInterDirc("use test")
  3873  	tk.MustInterDirc("drop causet if exists t1, t2, t3, t4, t5, t6, t7")
  3874  	tk.MustInterDirc("create causet t1(k int, v int)")
  3875  	tk.MustInterDirc("create causet t2(k int, v int)")
  3876  	tk.MustInterDirc("create causet t3(id int auto_increment, k int, v int, primary key(id))")
  3877  	tk.MustInterDirc("create causet t4(k int, v int)")
  3878  	tk.MustInterDirc("create causet t5(v int, k int, primary key(k))")
  3879  	tk.MustInterDirc("insert into t1 values (1, 1)")
  3880  	tk.MustInterDirc("insert into t4 values (3, 3)")
  3881  	tk.MustInterDirc("create causet t6 (id int, v longtext)")
  3882  	tk.MustInterDirc("create causet t7 (x int, id int, v longtext, primary key(id))")
  3883  
  3884  	// test the normal case that uFIDelate one event for a single causet.
  3885  	tk.MustInterDirc("uFIDelate t1 set v = 0 where k = 1")
  3886  	tk.MustQuery("select k, v from t1 where k = 1").Check(testkit.Rows("1 0"))
  3887  
  3888  	// test the case that the causet with auto_increment or none-null defCausumns as the right causet of left join.
  3889  	tk.MustInterDirc("uFIDelate t1 left join t3 on t1.k = t3.k set t1.v = 1")
  3890  	tk.MustQuery("select k, v from t1").Check(testkit.Rows("1 1"))
  3891  	tk.MustQuery("select id, k, v from t3").Check(testkit.Rows())
  3892  
  3893  	// test left join and the case that the right causet has no matching record but has uFIDelated the right causet defCausumns.
  3894  	tk.MustInterDirc("uFIDelate t1 left join t2 on t1.k = t2.k set t1.v = t2.v, t2.v = 3")
  3895  	tk.MustQuery("select k, v from t1").Check(testkit.Rows("1 <nil>"))
  3896  	tk.MustQuery("select k, v from t2").Check(testkit.Rows())
  3897  
  3898  	// test the case that the uFIDelate operation in the left causet references data in the right causet while data of the right causet defCausumns is modified.
  3899  	tk.MustInterDirc("uFIDelate t1 left join t2 on t1.k = t2.k set t2.v = 3, t1.v = t2.v")
  3900  	tk.MustQuery("select k, v from t1").Check(testkit.Rows("1 <nil>"))
  3901  	tk.MustQuery("select k, v from t2").Check(testkit.Rows())
  3902  
  3903  	// test right join and the case that the left causet has no matching record but has uFIDelated the left causet defCausumns.
  3904  	tk.MustInterDirc("uFIDelate t2 right join t1 on t2.k = t1.k set t2.v = 4, t1.v = 0")
  3905  	tk.MustQuery("select k, v from t1").Check(testkit.Rows("1 0"))
  3906  	tk.MustQuery("select k, v from t2").Check(testkit.Rows())
  3907  
  3908  	// test the case of right join and left join at the same time.
  3909  	tk.MustInterDirc("uFIDelate t1 left join t2 on t1.k = t2.k right join t4 on t4.k = t2.k set t1.v = 4, t2.v = 4, t4.v = 4")
  3910  	tk.MustQuery("select k, v from t1").Check(testkit.Rows("1 0"))
  3911  	tk.MustQuery("select k, v from t2").Check(testkit.Rows())
  3912  	tk.MustQuery("select k, v from t4").Check(testkit.Rows("3 4"))
  3913  
  3914  	// test normal left join and the case that the right causet has matching rows.
  3915  	tk.MustInterDirc("insert t2 values (1, 10)")
  3916  	tk.MustInterDirc("uFIDelate t1 left join t2 on t1.k = t2.k set t2.v = 11")
  3917  	tk.MustQuery("select k, v from t2").Check(testkit.Rows("1 11"))
  3918  
  3919  	// test the case of continuously joining the same causet and uFIDelating the unmatching records.
  3920  	tk.MustInterDirc("uFIDelate t1 t11 left join t2 on t11.k = t2.k left join t1 t12 on t2.v = t12.k set t12.v = 233, t11.v = 111")
  3921  	tk.MustQuery("select k, v from t1").Check(testkit.Rows("1 111"))
  3922  	tk.MustQuery("select k, v from t2").Check(testkit.Rows("1 11"))
  3923  
  3924  	// test the left join case that the left causet has records but all records are null.
  3925  	tk.MustInterDirc("delete from t1")
  3926  	tk.MustInterDirc("delete from t2")
  3927  	tk.MustInterDirc("insert into t1 values (null, null)")
  3928  	tk.MustInterDirc("uFIDelate t1 left join t2 on t1.k = t2.k set t1.v = 1")
  3929  	tk.MustQuery("select k, v from t1").Check(testkit.Rows("<nil> 1"))
  3930  
  3931  	// test the case that the right causet of left join has an primary key.
  3932  	tk.MustInterDirc("insert t5 values(0, 0)")
  3933  	tk.MustInterDirc("uFIDelate t1 left join t5 on t1.k = t5.k set t1.v = 2")
  3934  	tk.MustQuery("select k, v from t1").Check(testkit.Rows("<nil> 2"))
  3935  	tk.MustQuery("select k, v from t5").Check(testkit.Rows("0 0"))
  3936  
  3937  	tk.MustInterDirc("insert into t6 values (1, NULL)")
  3938  	tk.MustInterDirc("insert into t7 values (5, 1, 'a')")
  3939  	tk.MustInterDirc("uFIDelate t6, t7 set t6.v = t7.v where t6.id = t7.id and t7.x = 5")
  3940  	tk.MustQuery("select v from t6").Check(testkit.Rows("a"))
  3941  }
  3942  
  3943  func (s *testSuite3) TestMaxOneRow(c *C) {
  3944  	tk := testkit.NewTestKit(c, s.causetstore)
  3945  	tk.MustInterDirc(`use test`)
  3946  	tk.MustInterDirc(`drop causet if exists t1`)
  3947  	tk.MustInterDirc(`drop causet if exists t2`)
  3948  	tk.MustInterDirc(`create causet t1(a double, b double);`)
  3949  	tk.MustInterDirc(`create causet t2(a double, b double);`)
  3950  	tk.MustInterDirc(`insert into t1 values(1, 1), (2, 2), (3, 3);`)
  3951  	tk.MustInterDirc(`insert into t2 values(0, 0);`)
  3952  	tk.MustInterDirc(`set @@milevadb_init_chunk_size=1;`)
  3953  	rs, err := tk.InterDirc(`select (select t1.a from t1 where t1.a > t2.a) as a from t2;`)
  3954  	c.Assert(err, IsNil)
  3955  
  3956  	err = rs.Next(context.TODO(), rs.NewChunk())
  3957  	c.Assert(err.Error(), Equals, "subquery returns more than 1 event")
  3958  
  3959  	err = rs.Close()
  3960  	c.Assert(err, IsNil)
  3961  }
  3962  
  3963  func (s *testSuiteP2) TestCurrentTimestampValueSelection(c *C) {
  3964  	tk := testkit.NewTestKit(c, s.causetstore)
  3965  	tk.MustInterDirc("use test")
  3966  	tk.MustInterDirc("drop causet if exists t,t1")
  3967  
  3968  	tk.MustInterDirc("create causet t (id int, t0 timestamp null default current_timestamp, t1 timestamp(1) null default current_timestamp(1), t2 timestamp(2) null default current_timestamp(2) on uFIDelate current_timestamp(2))")
  3969  	tk.MustInterDirc("insert into t (id) values (1)")
  3970  	rs := tk.MustQuery("select t0, t1, t2 from t where id = 1")
  3971  	t0 := rs.Rows()[0][0].(string)
  3972  	t1 := rs.Rows()[0][1].(string)
  3973  	t2 := rs.Rows()[0][2].(string)
  3974  	c.Assert(len(strings.Split(t0, ".")), Equals, 1)
  3975  	c.Assert(len(strings.Split(t1, ".")[1]), Equals, 1)
  3976  	c.Assert(len(strings.Split(t2, ".")[1]), Equals, 2)
  3977  	tk.MustQuery("select id from t where t0 = ?", t0).Check(testkit.Rows("1"))
  3978  	tk.MustQuery("select id from t where t1 = ?", t1).Check(testkit.Rows("1"))
  3979  	tk.MustQuery("select id from t where t2 = ?", t2).Check(testkit.Rows("1"))
  3980  	time.Sleep(time.Second)
  3981  	tk.MustInterDirc("uFIDelate t set t0 = now() where id = 1")
  3982  	rs = tk.MustQuery("select t2 from t where id = 1")
  3983  	newT2 := rs.Rows()[0][0].(string)
  3984  	c.Assert(newT2 != t2, IsTrue)
  3985  
  3986  	tk.MustInterDirc("create causet t1 (id int, a timestamp, b timestamp(2), c timestamp(3))")
  3987  	tk.MustInterDirc("insert into t1 (id, a, b, c) values (1, current_timestamp(2), current_timestamp, current_timestamp(3))")
  3988  	rs = tk.MustQuery("select a, b, c from t1 where id = 1")
  3989  	a := rs.Rows()[0][0].(string)
  3990  	b := rs.Rows()[0][1].(string)
  3991  	d := rs.Rows()[0][2].(string)
  3992  	c.Assert(len(strings.Split(a, ".")), Equals, 1)
  3993  	c.Assert(strings.Split(b, ".")[1], Equals, "00")
  3994  	c.Assert(len(strings.Split(d, ".")[1]), Equals, 3)
  3995  }
  3996  
  3997  func (s *testSuite3) TestRowID(c *C) {
  3998  	tk := testkit.NewTestKit(c, s.causetstore)
  3999  	tk.MustInterDirc(`use test`)
  4000  	tk.MustInterDirc(`drop causet if exists t`)
  4001  	tk.MustInterDirc(`set @@milevadb_enable_clustered_index=0;`)
  4002  	tk.MustInterDirc(`create causet t(a varchar(10), b varchar(10), c varchar(1), index idx(a, b, c));`)
  4003  	tk.MustInterDirc(`insert into t values('a', 'b', 'c');`)
  4004  	tk.MustInterDirc(`insert into t values('a', 'b', 'c');`)
  4005  	tk.MustQuery(`select b, _milevadb_rowid from t use index(idx) where a = 'a';`).Check(testkit.Rows(
  4006  		`b 1`,
  4007  		`b 2`,
  4008  	))
  4009  	tk.MustInterDirc(`begin;`)
  4010  	tk.MustInterDirc(`select * from t for uFIDelate`)
  4011  	tk.MustQuery(`select distinct b from t use index(idx) where a = 'a';`).Check(testkit.Rows(`b`))
  4012  	tk.MustInterDirc(`commit;`)
  4013  
  4014  	tk.MustInterDirc(`drop causet if exists t`)
  4015  	tk.MustInterDirc(`create causet t(a varchar(5) primary key)`)
  4016  	tk.MustInterDirc(`insert into t values('a')`)
  4017  	tk.MustQuery("select *, _milevadb_rowid from t use index(`primary`) where _milevadb_rowid=1").Check(testkit.Rows("a 1"))
  4018  }
  4019  
  4020  func (s *testSuite3) TestDoSubquery(c *C) {
  4021  	tk := testkit.NewTestKit(c, s.causetstore)
  4022  	tk.MustInterDirc(`use test`)
  4023  	tk.MustInterDirc(`drop causet if exists t`)
  4024  	tk.MustInterDirc(`create causet t(a int)`)
  4025  	_, err := tk.InterDirc(`do 1 in (select * from t)`)
  4026  	c.Assert(err, IsNil, Commentf("err %v", err))
  4027  	tk.MustInterDirc(`insert into t values(1)`)
  4028  	r, err := tk.InterDirc(`do 1 in (select * from t)`)
  4029  	c.Assert(err, IsNil, Commentf("err %v", err))
  4030  	c.Assert(r, IsNil, Commentf("result of Do not empty"))
  4031  }
  4032  
  4033  func (s *testSerialSuite) TestTSOFail(c *C) {
  4034  	tk := testkit.NewTestKit(c, s.causetstore)
  4035  	tk.MustInterDirc(`use test`)
  4036  	tk.MustInterDirc(`drop causet if exists t`)
  4037  	tk.MustInterDirc(`create causet t(a int)`)
  4038  
  4039  	c.Assert(failpoint.Enable("github.com/whtcorpsinc/milevadb/stochastik/mockGetTSFail", "return"), IsNil)
  4040  	ctx := failpoint.WithHook(context.Background(), func(ctx context.Context, fpname string) bool {
  4041  		return fpname == "github.com/whtcorpsinc/milevadb/stochastik/mockGetTSFail"
  4042  	})
  4043  	_, err := tk.Se.InterDircute(ctx, `select * from t`)
  4044  	c.Assert(err, NotNil)
  4045  	c.Assert(failpoint.Disable("github.com/whtcorpsinc/milevadb/stochastik/mockGetTSFail"), IsNil)
  4046  }
  4047  
  4048  func (s *testSuite3) TestSelectHashPartitionBlock(c *C) {
  4049  	tk := testkit.NewTestKit(c, s.causetstore)
  4050  	tk.MustInterDirc(`use test`)
  4051  	tk.MustInterDirc(`drop causet if exists th`)
  4052  	tk.MustInterDirc("set @@stochastik.milevadb_enable_block_partition = '1';")
  4053  	tk.MustInterDirc(`create causet th (a int, b int) partition by hash(a) partitions 3;`)
  4054  	defer tk.MustInterDirc(`drop causet if exists th`)
  4055  	tk.MustInterDirc(`insert into th values (0,0),(1,1),(2,2),(3,3),(4,4),(5,5),(6,6),(7,7),(8,8);`)
  4056  	tk.MustInterDirc("insert into th values (-1,-1),(-2,-2),(-3,-3),(-4,-4),(-5,-5),(-6,-6),(-7,-7),(-8,-8);")
  4057  	tk.MustQuery("select b from th order by a").Check(testkit.Rows("-8", "-7", "-6", "-5", "-4", "-3", "-2", "-1", "0", "1", "2", "3", "4", "5", "6", "7", "8"))
  4058  	tk.MustQuery(" select * from th where a=-2;").Check(testkit.Rows("-2 -2"))
  4059  	tk.MustQuery(" select * from th where a=5;").Check(testkit.Rows("5 5"))
  4060  }
  4061  
  4062  func (s *testSuiteP1) TestSelectPartition(c *C) {
  4063  	tk := testkit.NewTestKit(c, s.causetstore)
  4064  	tk.MustInterDirc(`use test`)
  4065  	tk.MustInterDirc(`drop causet if exists th, tr`)
  4066  	tk.MustInterDirc("set @@stochastik.milevadb_enable_block_partition = '1';")
  4067  	tk.MustInterDirc(`create causet th (a int, b int) partition by hash(a) partitions 3;`)
  4068  	tk.MustInterDirc(`create causet tr (a int, b int)
  4069  							partition by range (a) (
  4070  							partition r0 values less than (4),
  4071  							partition r1 values less than (7),
  4072  							partition r3 values less than maxvalue)`)
  4073  	defer tk.MustInterDirc(`drop causet if exists th, tr`)
  4074  	tk.MustInterDirc(`insert into th values (0,0),(1,1),(2,2),(3,3),(4,4),(5,5),(6,6),(7,7),(8,8);`)
  4075  	tk.MustInterDirc("insert into th values (-1,-1),(-2,-2),(-3,-3),(-4,-4),(-5,-5),(-6,-6),(-7,-7),(-8,-8);")
  4076  	tk.MustInterDirc(`insert into tr values (-3,-3),(3,3),(4,4),(7,7),(8,8);`)
  4077  	// select 1 partition.
  4078  	tk.MustQuery("select b from th partition (p0) order by a").Check(testkit.Rows("-6", "-3", "0", "3", "6"))
  4079  	tk.MustQuery("select b from tr partition (r0) order by a").Check(testkit.Rows("-3", "3"))
  4080  	tk.MustQuery("select b from th partition (p0,P0) order by a").Check(testkit.Rows("-6", "-3", "0", "3", "6"))
  4081  	tk.MustQuery("select b from tr partition (r0,R0,r0) order by a").Check(testkit.Rows("-3", "3"))
  4082  	// select multi partition.
  4083  	tk.MustQuery("select b from th partition (P2,p0) order by a").Check(testkit.Rows("-8", "-6", "-5", "-3", "-2", "0", "2", "3", "5", "6", "8"))
  4084  	tk.MustQuery("select b from tr partition (r1,R3) order by a").Check(testkit.Rows("4", "7", "8"))
  4085  
  4086  	// test select unknown partition error
  4087  	err := tk.InterDircToErr("select b from th partition (p0,p4)")
  4088  	c.Assert(err.Error(), Equals, "[causet:1735]Unknown partition 'p4' in causet 'th'")
  4089  	err = tk.InterDircToErr("select b from tr partition (r1,r4)")
  4090  	c.Assert(err.Error(), Equals, "[causet:1735]Unknown partition 'r4' in causet 'tr'")
  4091  
  4092  	// test select partition causet in transaction.
  4093  	tk.MustInterDirc("begin")
  4094  	tk.MustInterDirc("insert into th values (10,10),(11,11)")
  4095  	tk.MustQuery("select a, b from th where b>10").Check(testkit.Rows("11 11"))
  4096  	tk.MustInterDirc("commit")
  4097  	tk.MustQuery("select a, b from th where b>10").Check(testkit.Rows("11 11"))
  4098  }
  4099  
  4100  func (s *testSuiteP1) TestDeletePartition(c *C) {
  4101  	tk := testkit.NewTestKit(c, s.causetstore)
  4102  	tk.MustInterDirc(`use test`)
  4103  	tk.MustInterDirc(`drop causet if exists t1`)
  4104  	tk.MustInterDirc(`create causet t1 (a int) partition by range (a) (
  4105   partition p0 values less than (10),
  4106   partition p1 values less than (20),
  4107   partition p2 values less than (30),
  4108   partition p3 values less than (40),
  4109   partition p4 values less than MAXVALUE
  4110   )`)
  4111  	tk.MustInterDirc("insert into t1 values (1),(11),(21),(31)")
  4112  	tk.MustInterDirc("delete from t1 partition (p4)")
  4113  	tk.MustQuery("select * from t1 order by a").Check(testkit.Rows("1", "11", "21", "31"))
  4114  	tk.MustInterDirc("delete from t1 partition (p0) where a > 10")
  4115  	tk.MustQuery("select * from t1 order by a").Check(testkit.Rows("1", "11", "21", "31"))
  4116  	tk.MustInterDirc("delete from t1 partition (p0,p1,p2)")
  4117  	tk.MustQuery("select * from t1").Check(testkit.Rows("31"))
  4118  }
  4119  
  4120  func (s *testSuite) TestSelectView(c *C) {
  4121  	tk := testkit.NewTestKit(c, s.causetstore)
  4122  	tk.MustInterDirc("use test")
  4123  	tk.MustInterDirc("create causet view_t (a int,b int)")
  4124  	tk.MustInterDirc("insert into view_t values(1,2)")
  4125  	tk.MustInterDirc("create definer='root'@'localhost' view view1 as select * from view_t")
  4126  	tk.MustInterDirc("create definer='root'@'localhost' view view2(c,d) as select * from view_t")
  4127  	tk.MustInterDirc("create definer='root'@'localhost' view view3(c,d) as select a,b from view_t")
  4128  	tk.MustQuery("select * from view1;").Check(testkit.Rows("1 2"))
  4129  	tk.MustQuery("select * from view2;").Check(testkit.Rows("1 2"))
  4130  	tk.MustQuery("select * from view3;").Check(testkit.Rows("1 2"))
  4131  	tk.MustInterDirc("drop causet view_t;")
  4132  	tk.MustInterDirc("create causet view_t(c int,d int)")
  4133  	err := tk.InterDircToErr("select * from view1")
  4134  	c.Assert(err.Error(), Equals, "[causet:1356]View 'test.view1' references invalid causet(s) or defCausumn(s) or function(s) or definer/invoker of view lack rights to use them")
  4135  	err = tk.InterDircToErr("select * from view2")
  4136  	c.Assert(err.Error(), Equals, "[causet:1356]View 'test.view2' references invalid causet(s) or defCausumn(s) or function(s) or definer/invoker of view lack rights to use them")
  4137  	err = tk.InterDircToErr("select * from view3")
  4138  	c.Assert(err.Error(), Equals, causetembedded.ErrViewInvalid.GenWithStackByArgs("test", "view3").Error())
  4139  	tk.MustInterDirc("drop causet view_t;")
  4140  	tk.MustInterDirc("create causet view_t(a int,b int,c int)")
  4141  	tk.MustInterDirc("insert into view_t values(1,2,3)")
  4142  	tk.MustQuery("select * from view1;").Check(testkit.Rows("1 2"))
  4143  	tk.MustQuery("select * from view2;").Check(testkit.Rows("1 2"))
  4144  	tk.MustQuery("select * from view3;").Check(testkit.Rows("1 2"))
  4145  	tk.MustInterDirc("alter causet view_t drop defCausumn a")
  4146  	tk.MustInterDirc("alter causet view_t add defCausumn a int after b")
  4147  	tk.MustInterDirc("uFIDelate view_t set a=1;")
  4148  	tk.MustQuery("select * from view1;").Check(testkit.Rows("1 2"))
  4149  	tk.MustQuery("select * from view2;").Check(testkit.Rows("1 2"))
  4150  	tk.MustQuery("select * from view3;").Check(testkit.Rows("1 2"))
  4151  	tk.MustInterDirc("drop causet view_t;")
  4152  	tk.MustInterDirc("drop view view1,view2,view3;")
  4153  
  4154  	tk.MustInterDirc("set @@milevadb_enable_window_function = 1")
  4155  	defer func() {
  4156  		tk.MustInterDirc("set @@milevadb_enable_window_function = 0")
  4157  	}()
  4158  	tk.MustInterDirc("create causet t(a int, b int)")
  4159  	tk.MustInterDirc("insert into t values (1,1),(1,2),(2,1),(2,2)")
  4160  	tk.MustInterDirc("create definer='root'@'localhost' view v as select a, first_value(a) over(rows between 1 preceding and 1 following), last_value(a) over(rows between 1 preceding and 1 following) from t")
  4161  	result := tk.MustQuery("select * from v")
  4162  	result.Check(testkit.Rows("1 1 1", "1 1 2", "2 1 2", "2 2 2"))
  4163  	tk.MustInterDirc("drop view v;")
  4164  }
  4165  
  4166  type testSuite2 struct {
  4167  	*baseTestSuite
  4168  }
  4169  
  4170  func (s *testSuite2) TearDownTest(c *C) {
  4171  	tk := testkit.NewTestKit(c, s.causetstore)
  4172  	tk.MustInterDirc("use test")
  4173  	r := tk.MustQuery("show full blocks")
  4174  	for _, tb := range r.Rows() {
  4175  		blockName := tb[0]
  4176  		if tb[1] == "VIEW" {
  4177  			tk.MustInterDirc(fmt.Sprintf("drop view %v", blockName))
  4178  		} else if tb[1] == "SEQUENCE" {
  4179  			tk.MustInterDirc(fmt.Sprintf("drop sequence %v", blockName))
  4180  		} else {
  4181  			tk.MustInterDirc(fmt.Sprintf("drop causet %v", blockName))
  4182  		}
  4183  	}
  4184  }
  4185  
  4186  type testSuite3 struct {
  4187  	*baseTestSuite
  4188  }
  4189  
  4190  func (s *testSuite3) TearDownTest(c *C) {
  4191  	tk := testkit.NewTestKit(c, s.causetstore)
  4192  	tk.MustInterDirc("use test")
  4193  	r := tk.MustQuery("show full blocks")
  4194  	for _, tb := range r.Rows() {
  4195  		blockName := tb[0]
  4196  		if tb[1] == "VIEW" {
  4197  			tk.MustInterDirc(fmt.Sprintf("drop view %v", blockName))
  4198  		} else if tb[1] == "SEQUENCE" {
  4199  			tk.MustInterDirc(fmt.Sprintf("drop sequence %v", blockName))
  4200  		} else {
  4201  			tk.MustInterDirc(fmt.Sprintf("drop causet %v", blockName))
  4202  		}
  4203  	}
  4204  }
  4205  
  4206  type testSuite4 struct {
  4207  	*baseTestSuite
  4208  }
  4209  
  4210  func (s *testSuite4) TearDownTest(c *C) {
  4211  	tk := testkit.NewTestKit(c, s.causetstore)
  4212  	tk.MustInterDirc("use test")
  4213  	r := tk.MustQuery("show full blocks")
  4214  	for _, tb := range r.Rows() {
  4215  		blockName := tb[0]
  4216  		if tb[1] == "VIEW" {
  4217  			tk.MustInterDirc(fmt.Sprintf("drop view %v", blockName))
  4218  		} else if tb[1] == "SEQUENCE" {
  4219  			tk.MustInterDirc(fmt.Sprintf("drop sequence %v", blockName))
  4220  		} else {
  4221  			tk.MustInterDirc(fmt.Sprintf("drop causet %v", blockName))
  4222  		}
  4223  	}
  4224  }
  4225  
  4226  type testSuite5 struct {
  4227  	*baseTestSuite
  4228  }
  4229  
  4230  func (s *testSuite5) TearDownTest(c *C) {
  4231  	tk := testkit.NewTestKit(c, s.causetstore)
  4232  	tk.MustInterDirc("use test")
  4233  	r := tk.MustQuery("show full blocks")
  4234  	for _, tb := range r.Rows() {
  4235  		blockName := tb[0]
  4236  		if tb[1] == "VIEW" {
  4237  			tk.MustInterDirc(fmt.Sprintf("drop view %v", blockName))
  4238  		} else if tb[1] == "SEQUENCE" {
  4239  			tk.MustInterDirc(fmt.Sprintf("drop sequence %v", blockName))
  4240  		} else {
  4241  			tk.MustInterDirc(fmt.Sprintf("drop causet %v", blockName))
  4242  		}
  4243  	}
  4244  }
  4245  
  4246  type testSuite6 struct {
  4247  	*baseTestSuite
  4248  }
  4249  
  4250  func (s *testSuite6) TearDownTest(c *C) {
  4251  	tk := testkit.NewTestKit(c, s.causetstore)
  4252  	tk.MustInterDirc("use test")
  4253  	r := tk.MustQuery("show full blocks")
  4254  	for _, tb := range r.Rows() {
  4255  		blockName := tb[0]
  4256  		if tb[1] == "VIEW" {
  4257  			tk.MustInterDirc(fmt.Sprintf("drop view %v", blockName))
  4258  		} else if tb[1] == "SEQUENCE" {
  4259  			tk.MustInterDirc(fmt.Sprintf("drop sequence %v", blockName))
  4260  		} else {
  4261  			tk.MustInterDirc(fmt.Sprintf("drop causet %v", blockName))
  4262  		}
  4263  	}
  4264  }
  4265  
  4266  type testSuite7 struct {
  4267  	*baseTestSuite
  4268  }
  4269  
  4270  func (s *testSuite7) TearDownTest(c *C) {
  4271  	tk := testkit.NewTestKit(c, s.causetstore)
  4272  	tk.MustInterDirc("use test")
  4273  	r := tk.MustQuery("show full blocks")
  4274  	for _, tb := range r.Rows() {
  4275  		blockName := tb[0]
  4276  		if tb[1] == "VIEW" {
  4277  			tk.MustInterDirc(fmt.Sprintf("drop view %v", blockName))
  4278  		} else if tb[1] == "SEQUENCE" {
  4279  			tk.MustInterDirc(fmt.Sprintf("drop sequence %v", blockName))
  4280  		} else {
  4281  			tk.MustInterDirc(fmt.Sprintf("drop causet %v", blockName))
  4282  		}
  4283  	}
  4284  }
  4285  
  4286  type testSuite8 struct {
  4287  	*baseTestSuite
  4288  }
  4289  
  4290  func (s *testSuite8) TearDownTest(c *C) {
  4291  	tk := testkit.NewTestKit(c, s.causetstore)
  4292  	tk.MustInterDirc("use test")
  4293  	r := tk.MustQuery("show full blocks")
  4294  	for _, tb := range r.Rows() {
  4295  		blockName := tb[0]
  4296  		if tb[1] == "VIEW" {
  4297  			tk.MustInterDirc(fmt.Sprintf("drop view %v", blockName))
  4298  		} else if tb[1] == "SEQUENCE" {
  4299  			tk.MustInterDirc(fmt.Sprintf("drop sequence %v", blockName))
  4300  		} else {
  4301  			tk.MustInterDirc(fmt.Sprintf("drop causet %v", blockName))
  4302  		}
  4303  	}
  4304  }
  4305  
  4306  type testSerialSuite1 struct {
  4307  	*baseTestSuite
  4308  }
  4309  
  4310  func (s *testSerialSuite1) TearDownTest(c *C) {
  4311  	tk := testkit.NewTestKit(c, s.causetstore)
  4312  	tk.MustInterDirc("use test")
  4313  	r := tk.MustQuery("show full blocks")
  4314  	for _, tb := range r.Rows() {
  4315  		blockName := tb[0]
  4316  		if tb[1] == "VIEW" {
  4317  			tk.MustInterDirc(fmt.Sprintf("drop view %v", blockName))
  4318  		} else if tb[1] == "SEQUENCE" {
  4319  			tk.MustInterDirc(fmt.Sprintf("drop sequence %v", blockName))
  4320  		} else {
  4321  			tk.MustInterDirc(fmt.Sprintf("drop causet %v", blockName))
  4322  		}
  4323  	}
  4324  }
  4325  
  4326  func (s *testSuiteP2) TestStrToDateBuiltin(c *C) {
  4327  	tk := testkit.NewTestKit(c, s.causetstore)
  4328  	tk.MustQuery(`select str_to_date('20190101','%Y%m%d%!') from dual`).Check(testkit.Rows("2020-01-01"))
  4329  	tk.MustQuery(`select str_to_date('20190101','%Y%m%d%f') from dual`).Check(testkit.Rows("2020-01-01 00:00:00.000000"))
  4330  	tk.MustQuery(`select str_to_date('20190101','%Y%m%d%H%i%s') from dual`).Check(testkit.Rows("2020-01-01 00:00:00"))
  4331  	tk.MustQuery(`select str_to_date('18/10/22','%y/%m/%d') from dual`).Check(testkit.Rows("2020-10-22"))
  4332  	tk.MustQuery(`select str_to_date('a18/10/22','%y/%m/%d') from dual`).Check(testkit.Rows("<nil>"))
  4333  	tk.MustQuery(`select str_to_date('69/10/22','%y/%m/%d') from dual`).Check(testkit.Rows("2069-10-22"))
  4334  	tk.MustQuery(`select str_to_date('70/10/22','%y/%m/%d') from dual`).Check(testkit.Rows("1970-10-22"))
  4335  	tk.MustQuery(`select str_to_date('8/10/22','%y/%m/%d') from dual`).Check(testkit.Rows("2008-10-22"))
  4336  	tk.MustQuery(`select str_to_date('8/10/22','%Y/%m/%d') from dual`).Check(testkit.Rows("2008-10-22"))
  4337  	tk.MustQuery(`select str_to_date('18/10/22','%Y/%m/%d') from dual`).Check(testkit.Rows("2020-10-22"))
  4338  	tk.MustQuery(`select str_to_date('a18/10/22','%Y/%m/%d') from dual`).Check(testkit.Rows("<nil>"))
  4339  	tk.MustQuery(`select str_to_date('69/10/22','%Y/%m/%d') from dual`).Check(testkit.Rows("2069-10-22"))
  4340  	tk.MustQuery(`select str_to_date('70/10/22','%Y/%m/%d') from dual`).Check(testkit.Rows("1970-10-22"))
  4341  	tk.MustQuery(`select str_to_date('018/10/22','%Y/%m/%d') from dual`).Check(testkit.Rows("0018-10-22"))
  4342  	tk.MustQuery(`select str_to_date('2020/10/22','%Y/%m/%d') from dual`).Check(testkit.Rows("2020-10-22"))
  4343  	tk.MustQuery(`select str_to_date('018/10/22','%y/%m/%d') from dual`).Check(testkit.Rows("<nil>"))
  4344  	tk.MustQuery(`select str_to_date('18/10/22','%y0/%m/%d') from dual`).Check(testkit.Rows("<nil>"))
  4345  	tk.MustQuery(`select str_to_date('18/10/22','%Y0/%m/%d') from dual`).Check(testkit.Rows("<nil>"))
  4346  	tk.MustQuery(`select str_to_date('18a/10/22','%y/%m/%d') from dual`).Check(testkit.Rows("<nil>"))
  4347  	tk.MustQuery(`select str_to_date('18a/10/22','%Y/%m/%d') from dual`).Check(testkit.Rows("<nil>"))
  4348  	tk.MustQuery(`select str_to_date('20188/10/22','%Y/%m/%d') from dual`).Check(testkit.Rows("<nil>"))
  4349  	tk.MustQuery(`select str_to_date('2018510522','%Y5%m5%d') from dual`).Check(testkit.Rows("2020-10-22"))
  4350  	tk.MustQuery(`select str_to_date('2020^10^22','%Y^%m^%d') from dual`).Check(testkit.Rows("2020-10-22"))
  4351  	tk.MustQuery(`select str_to_date('2020@10@22','%Y@%m@%d') from dual`).Check(testkit.Rows("2020-10-22"))
  4352  	tk.MustQuery(`select str_to_date('2020%10%22','%Y%%m%%d') from dual`).Check(testkit.Rows("<nil>"))
  4353  	tk.MustQuery(`select str_to_date('2020(10(22','%Y(%m(%d') from dual`).Check(testkit.Rows("2020-10-22"))
  4354  	tk.MustQuery(`select str_to_date('2020\10\22','%Y\%m\%d') from dual`).Check(testkit.Rows("<nil>"))
  4355  	tk.MustQuery(`select str_to_date('2020=10=22','%Y=%m=%d') from dual`).Check(testkit.Rows("2020-10-22"))
  4356  	tk.MustQuery(`select str_to_date('2020+10+22','%Y+%m+%d') from dual`).Check(testkit.Rows("2020-10-22"))
  4357  	tk.MustQuery(`select str_to_date('2018_10_22','%Y_%m_%d') from dual`).Check(testkit.Rows("2020-10-22"))
  4358  	tk.MustQuery(`select str_to_date('69510522','%y5%m5%d') from dual`).Check(testkit.Rows("2069-10-22"))
  4359  	tk.MustQuery(`select str_to_date('69^10^22','%y^%m^%d') from dual`).Check(testkit.Rows("2069-10-22"))
  4360  	tk.MustQuery(`select str_to_date('18@10@22','%y@%m@%d') from dual`).Check(testkit.Rows("2020-10-22"))
  4361  	tk.MustQuery(`select str_to_date('18%10%22','%y%%m%%d') from dual`).Check(testkit.Rows("<nil>"))
  4362  	tk.MustQuery(`select str_to_date('18(10(22','%y(%m(%d') from dual`).Check(testkit.Rows("2020-10-22"))
  4363  	tk.MustQuery(`select str_to_date('18\10\22','%y\%m\%d') from dual`).Check(testkit.Rows("<nil>"))
  4364  	tk.MustQuery(`select str_to_date('18+10+22','%y+%m+%d') from dual`).Check(testkit.Rows("2020-10-22"))
  4365  	tk.MustQuery(`select str_to_date('18=10=22','%y=%m=%d') from dual`).Check(testkit.Rows("2020-10-22"))
  4366  	tk.MustQuery(`select str_to_date('18_10_22','%y_%m_%d') from dual`).Check(testkit.Rows("2020-10-22"))
  4367  	tk.MustQuery(`SELECT STR_TO_DATE('2020-07-04 11:22:33 PM', '%Y-%m-%d %r')`).Check(testkit.Rows("2020-07-04 23:22:33"))
  4368  	tk.MustQuery(`SELECT STR_TO_DATE('2020-07-04 12:22:33 AM', '%Y-%m-%d %r')`).Check(testkit.Rows("2020-07-04 00:22:33"))
  4369  	tk.MustQuery(`SELECT STR_TO_DATE('2020-07-04 12:22:33', '%Y-%m-%d %T')`).Check(testkit.Rows("2020-07-04 12:22:33"))
  4370  	tk.MustQuery(`SELECT STR_TO_DATE('2020-07-04 00:22:33', '%Y-%m-%d %T')`).Check(testkit.Rows("2020-07-04 00:22:33"))
  4371  }
  4372  
  4373  func (s *testSuiteP2) TestReadPartitionedBlock(c *C) {
  4374  	// Test three reader on partitioned causet.
  4375  	tk := testkit.NewTestKit(c, s.causetstore)
  4376  	tk.MustInterDirc("use test")
  4377  	tk.MustInterDirc("drop causet if exists pt")
  4378  	tk.MustInterDirc("create causet pt (a int, b int, index i_b(b)) partition by range (a) (partition p1 values less than (2), partition p2 values less than (4), partition p3 values less than (6))")
  4379  	for i := 0; i < 6; i++ {
  4380  		tk.MustInterDirc(fmt.Sprintf("insert into pt values(%d, %d)", i, i))
  4381  	}
  4382  	// Block reader
  4383  	tk.MustQuery("select * from pt order by a").Check(testkit.Rows("0 0", "1 1", "2 2", "3 3", "4 4", "5 5"))
  4384  	// Index reader
  4385  	tk.MustQuery("select b from pt where b = 3").Check(testkit.Rows("3"))
  4386  	// Index lookup
  4387  	tk.MustQuery("select a from pt where b = 3").Check(testkit.Rows("3"))
  4388  }
  4389  
  4390  func (s *testSplitBlock) TestSplitRegion(c *C) {
  4391  	tk := testkit.NewTestKit(c, s.causetstore)
  4392  	tk.MustInterDirc("use test")
  4393  	tk.MustInterDirc("drop causet if exists t, t1")
  4394  	tk.MustInterDirc("create causet t(a varchar(100),b int, index idx1(b,a))")
  4395  	tk.MustInterDirc(`split causet t index idx1 by (10000,"abcd"),(10000000);`)
  4396  	_, err := tk.InterDirc(`split causet t index idx1 by ("abcd");`)
  4397  	c.Assert(err, NotNil)
  4398  	terr := errors.Cause(err).(*terror.Error)
  4399  	c.Assert(terr.Code(), Equals, errors.ErrCode(allegrosql.WarnDataTruncated))
  4400  
  4401  	// Test for split index region.
  4402  	// Check min value is more than max value.
  4403  	tk.MustInterDirc(`split causet t index idx1 between (0) and (1000000000) regions 10`)
  4404  	_, err = tk.InterDirc(`split causet t index idx1 between (2,'a') and (1,'c') regions 10`)
  4405  	c.Assert(err, NotNil)
  4406  	c.Assert(err.Error(), Equals, "Split index `idx1` region lower value (2,a) should less than the upper value (1,c)")
  4407  
  4408  	// Check min value is invalid.
  4409  	_, err = tk.InterDirc(`split causet t index idx1 between () and (1) regions 10`)
  4410  	c.Assert(err, NotNil)
  4411  	c.Assert(err.Error(), Equals, "Split index `idx1` region lower value count should more than 0")
  4412  
  4413  	// Check max value is invalid.
  4414  	_, err = tk.InterDirc(`split causet t index idx1 between (1) and () regions 10`)
  4415  	c.Assert(err, NotNil)
  4416  	c.Assert(err.Error(), Equals, "Split index `idx1` region upper value count should more than 0")
  4417  
  4418  	// Check pre-split region num is too large.
  4419  	_, err = tk.InterDirc(`split causet t index idx1 between (0) and (1000000000) regions 10000`)
  4420  	c.Assert(err, NotNil)
  4421  	c.Assert(err.Error(), Equals, "Split index region num exceeded the limit 1000")
  4422  
  4423  	// Check pre-split region num 0 is invalid.
  4424  	_, err = tk.InterDirc(`split causet t index idx1 between (0) and (1000000000) regions 0`)
  4425  	c.Assert(err, NotNil)
  4426  	c.Assert(err.Error(), Equals, "Split index region num should more than 0")
  4427  
  4428  	// Test truncate error msg.
  4429  	_, err = tk.InterDirc(`split causet t index idx1 between ("aa") and (1000000000) regions 0`)
  4430  	c.Assert(err, NotNil)
  4431  	c.Assert(err.Error(), Equals, "[types:1265]Incorrect value: 'aa' for defCausumn 'b'")
  4432  
  4433  	// Test for split causet region.
  4434  	tk.MustInterDirc(`split causet t between (0) and (1000000000) regions 10`)
  4435  	// Check the lower value is more than the upper value.
  4436  	_, err = tk.InterDirc(`split causet t between (2) and (1) regions 10`)
  4437  	c.Assert(err, NotNil)
  4438  	c.Assert(err.Error(), Equals, "Split causet `t` region lower value 2 should less than the upper value 1")
  4439  
  4440  	// Check the lower value is invalid.
  4441  	_, err = tk.InterDirc(`split causet t between () and (1) regions 10`)
  4442  	c.Assert(err, NotNil)
  4443  	c.Assert(err.Error(), Equals, "Split causet region lower value count should be 1")
  4444  
  4445  	// Check upper value is invalid.
  4446  	_, err = tk.InterDirc(`split causet t between (1) and () regions 10`)
  4447  	c.Assert(err, NotNil)
  4448  	c.Assert(err.Error(), Equals, "Split causet region upper value count should be 1")
  4449  
  4450  	// Check pre-split region num is too large.
  4451  	_, err = tk.InterDirc(`split causet t between (0) and (1000000000) regions 10000`)
  4452  	c.Assert(err, NotNil)
  4453  	c.Assert(err.Error(), Equals, "Split causet region num exceeded the limit 1000")
  4454  
  4455  	// Check pre-split region num 0 is invalid.
  4456  	_, err = tk.InterDirc(`split causet t between (0) and (1000000000) regions 0`)
  4457  	c.Assert(err, NotNil)
  4458  	c.Assert(err.Error(), Equals, "Split causet region num should more than 0")
  4459  
  4460  	// Test truncate error msg.
  4461  	_, err = tk.InterDirc(`split causet t between ("aa") and (1000000000) regions 10`)
  4462  	c.Assert(err, NotNil)
  4463  	c.Assert(err.Error(), Equals, "[types:1265]Incorrect value: 'aa' for defCausumn '_milevadb_rowid'")
  4464  
  4465  	// Test split causet region step is too small.
  4466  	_, err = tk.InterDirc(`split causet t between (0) and (100) regions 10`)
  4467  	c.Assert(err, NotNil)
  4468  	c.Assert(err.Error(), Equals, "Split causet `t` region step value should more than 1000, step 10 is invalid")
  4469  
  4470  	// Test split region by syntax.
  4471  	tk.MustInterDirc(`split causet t by (0),(1000),(1000000)`)
  4472  
  4473  	// Test split region twice to test for multiple batch split region requests.
  4474  	tk.MustInterDirc("create causet t1(a int, b int)")
  4475  	tk.MustQuery("split causet t1 between(0) and (10000) regions 10;").Check(testkit.Rows("9 1"))
  4476  	tk.MustQuery("split causet t1 between(10) and (10010) regions 5;").Check(testkit.Rows("4 1"))
  4477  
  4478  	// Test split region for partition causet.
  4479  	tk.MustInterDirc("drop causet if exists t")
  4480  	tk.MustInterDirc("create causet t (a int,b int) partition by hash(a) partitions 5;")
  4481  	tk.MustQuery("split causet t between (0) and (1000000) regions 5;").Check(testkit.Rows("20 1"))
  4482  	// Test for `split for region` syntax.
  4483  	tk.MustQuery("split region for partition causet t between (1000000) and (100000000) regions 10;").Check(testkit.Rows("45 1"))
  4484  
  4485  	// Test split region for partition causet with specified partition.
  4486  	tk.MustQuery("split causet t partition (p1,p2) between (100000000) and (1000000000) regions 5;").Check(testkit.Rows("8 1"))
  4487  	// Test for `split for region` syntax.
  4488  	tk.MustQuery("split region for partition causet t partition (p3,p4) between (100000000) and (1000000000) regions 5;").Check(testkit.Rows("8 1"))
  4489  }
  4490  
  4491  func (s *testSplitBlock) TestClusterIndexSplitBlockIntegration(c *C) {
  4492  	tk := testkit.NewTestKit(c, s.causetstore)
  4493  	tk.MustInterDirc("drop database if exists test_cluster_index_index_split_block_integration;")
  4494  	tk.MustInterDirc("create database test_cluster_index_index_split_block_integration;")
  4495  	tk.MustInterDirc("use test_cluster_index_index_split_block_integration;")
  4496  	tk.MustInterDirc("set @@milevadb_enable_clustered_index=1;")
  4497  
  4498  	tk.MustInterDirc("create causet t (a varchar(255), b double, c int, primary key (a, b));")
  4499  
  4500  	// Value list length not match.
  4501  	lowerMsg := "Split causet region lower value count should be 2"
  4502  	upperMsg := "Split causet region upper value count should be 2"
  4503  	tk.MustGetErrMsg("split causet t between ('aaa') and ('aaa', 100.0) regions 10;", lowerMsg)
  4504  	tk.MustGetErrMsg("split causet t between ('aaa', 1.0) and ('aaa', 100.0, 11) regions 10;", upperMsg)
  4505  
  4506  	// Value type not match.
  4507  	errMsg := "[types:1265]Incorrect value: 'aaa' for defCausumn 'b'"
  4508  	tk.MustGetErrMsg("split causet t between ('aaa', 0.0) and (100.0, 'aaa') regions 10;", errMsg)
  4509  
  4510  	// lower bound >= upper bound.
  4511  	errMsg = "Split causet `t` region lower value (aaa,0) should less than the upper value (aaa,0)"
  4512  	tk.MustGetErrMsg("split causet t between ('aaa', 0.0) and ('aaa', 0.0) regions 10;", errMsg)
  4513  	errMsg = "Split causet `t` region lower value (bbb,0) should less than the upper value (aaa,0)"
  4514  	tk.MustGetErrMsg("split causet t between ('bbb', 0.0) and ('aaa', 0.0) regions 10;", errMsg)
  4515  
  4516  	// Exceed limit 1000.
  4517  	errMsg = "Split causet region num exceeded the limit 1000"
  4518  	tk.MustGetErrMsg("split causet t between ('aaa', 0.0) and ('aaa', 0.1) regions 100000;", errMsg)
  4519  
  4520  	// Success.
  4521  	tk.MustInterDirc("split causet t between ('aaa', 0.0) and ('aaa', 100.0) regions 10;")
  4522  	tk.MustInterDirc("split causet t by ('aaa', 0.0), ('aaa', 20.0), ('aaa', 100.0);")
  4523  	tk.MustInterDirc("split causet t by ('aaa', 100.0), ('qqq', 20.0), ('zzz', 100.0), ('zzz', 1000.0);")
  4524  
  4525  	tk.MustInterDirc("drop causet t;")
  4526  	tk.MustInterDirc("create causet t (a int, b int, c int, d int, primary key(a, c, d));")
  4527  	tk.MustQuery("split causet t between (0, 0, 0) and (0, 0, 1) regions 1000;").Check(testkit.Rows("999 1"))
  4528  
  4529  	tk.MustInterDirc("drop causet t;")
  4530  	tk.MustInterDirc("create causet t (a int, b int, c int, d int, primary key(d, a, c));")
  4531  	tk.MustQuery("split causet t by (0, 0, 0), (1, 2, 3), (65535, 65535, 65535);").Check(testkit.Rows("3 1"))
  4532  }
  4533  
  4534  func (s *testSplitBlock) TestClusterIndexShowBlockRegion(c *C) {
  4535  	tk := testkit.NewTestKit(c, s.causetstore)
  4536  	atomic.StoreUint32(&dbs.EnableSplitBlockRegion, 1)
  4537  	tk.MustInterDirc("set global milevadb_scatter_region = 1")
  4538  	tk.MustInterDirc("drop database if exists cluster_index_regions;")
  4539  	tk.MustInterDirc("create database cluster_index_regions;")
  4540  	tk.MustInterDirc("use cluster_index_regions;")
  4541  	tk.MustInterDirc("set @@milevadb_enable_clustered_index=1;")
  4542  	tk.MustInterDirc("create causet t (a int, b int, c int, primary key(a, b));")
  4543  	tk.MustInterDirc("insert t values (1, 1, 1), (2, 2, 2);")
  4544  	tk.MustQuery("split causet t between (1, 0) and (2, 3) regions 2;").Check(testkit.Rows("1 1"))
  4545  	rows := tk.MustQuery("show causet t regions").Rows()
  4546  	tbl := testGetBlockByName(c, tk.Se, "cluster_index_regions", "t")
  4547  	// Check the region start key.
  4548  	c.Assert(rows[0][1], Matches, fmt.Sprintf("t_%d_", tbl.Meta().ID))
  4549  	c.Assert(rows[1][1], Matches, fmt.Sprintf("t_%d_r_03800000000000000183800000000000", tbl.Meta().ID))
  4550  
  4551  	tk.MustInterDirc("drop causet t;")
  4552  	tk.MustInterDirc("create causet t (a int, b int);")
  4553  	tk.MustQuery("split causet t between (0) and (100000) regions 2;").Check(testkit.Rows("1 1"))
  4554  	rows = tk.MustQuery("show causet t regions").Rows()
  4555  	tbl = testGetBlockByName(c, tk.Se, "cluster_index_regions", "t")
  4556  	// Check the region start key is int64.
  4557  	c.Assert(rows[0][1], Matches, fmt.Sprintf("t_%d_", tbl.Meta().ID))
  4558  	c.Assert(rows[1][1], Matches, fmt.Sprintf("t_%d_r_50000", tbl.Meta().ID))
  4559  }
  4560  
  4561  func (s *testSuiteWithData) TestClusterIndexOuterJoinElimination(c *C) {
  4562  	tk := testkit.NewTestKit(c, s.causetstore)
  4563  	tk.MustInterDirc(`set @@milevadb_enable_clustered_index = 1`)
  4564  	tk.MustInterDirc("use test")
  4565  	tk.MustInterDirc("create causet t (a int, b int, c int, primary key(a,b))")
  4566  	rows := tk.MustQuery(`explain select t1.a from t t1 left join t t2 on t1.a = t2.a and t1.b = t2.b`).Rows()
  4567  	rowStrs := s.testData.ConvertRowsToStrings(rows)
  4568  	for _, event := range rowStrs {
  4569  		// outer join has been eliminated.
  4570  		c.Assert(strings.Index(event, "Join"), Equals, -1)
  4571  	}
  4572  }
  4573  
  4574  func (s *testSplitBlock) TestShowBlockRegion(c *C) {
  4575  	tk := testkit.NewTestKit(c, s.causetstore)
  4576  	tk.MustInterDirc("use test")
  4577  	tk.MustInterDirc("drop causet if exists t_regions")
  4578  	tk.MustInterDirc("set global milevadb_scatter_region = 1")
  4579  	atomic.StoreUint32(&dbs.EnableSplitBlockRegion, 1)
  4580  	tk.MustInterDirc("create causet t_regions (a int key, b int, c int, index idx(b), index idx2(c))")
  4581  	_, err := tk.InterDirc("split partition causet t_regions partition (p1,p2) index idx between (0) and (20000) regions 2;")
  4582  	c.Assert(err.Error(), Equals, causetembedded.ErrPartitionClauseOnNonpartitioned.Error())
  4583  
  4584  	// Test show causet regions.
  4585  	tk.MustQuery(`split causet t_regions between (-10000) and (10000) regions 4;`).Check(testkit.Rows("4 1"))
  4586  	re := tk.MustQuery("show causet t_regions regions")
  4587  	rows := re.Rows()
  4588  	// Block t_regions should have 5 regions now.
  4589  	// 4 regions to causetstore record data.
  4590  	// 1 region to causetstore index data.
  4591  	c.Assert(len(rows), Equals, 5)
  4592  	c.Assert(len(rows[0]), Equals, 11)
  4593  	tbl := testGetBlockByName(c, tk.Se, "test", "t_regions")
  4594  	// Check the region start key.
  4595  	c.Assert(rows[0][1], Equals, fmt.Sprintf("t_%d_r", tbl.Meta().ID))
  4596  	c.Assert(rows[1][1], Equals, fmt.Sprintf("t_%d_r_-5000", tbl.Meta().ID))
  4597  	c.Assert(rows[2][1], Equals, fmt.Sprintf("t_%d_r_0", tbl.Meta().ID))
  4598  	c.Assert(rows[3][1], Equals, fmt.Sprintf("t_%d_r_5000", tbl.Meta().ID))
  4599  	c.Assert(rows[4][2], Equals, fmt.Sprintf("t_%d_r", tbl.Meta().ID))
  4600  
  4601  	// Test show causet index regions.
  4602  	tk.MustQuery(`split causet t_regions index idx between (-1000) and (1000) regions 4;`).Check(testkit.Rows("4 1"))
  4603  	re = tk.MustQuery("show causet t_regions index idx regions")
  4604  	rows = re.Rows()
  4605  	// The index `idx` of causet t_regions should have 4 regions now.
  4606  	c.Assert(len(rows), Equals, 4)
  4607  	// Check the region start key.
  4608  	c.Assert(rows[0][1], Matches, fmt.Sprintf("t_%d.*", tbl.Meta().ID))
  4609  	c.Assert(rows[1][1], Matches, fmt.Sprintf("t_%d_i_1_.*", tbl.Meta().ID))
  4610  	c.Assert(rows[2][1], Matches, fmt.Sprintf("t_%d_i_1_.*", tbl.Meta().ID))
  4611  	c.Assert(rows[3][1], Matches, fmt.Sprintf("t_%d_i_1_.*", tbl.Meta().ID))
  4612  
  4613  	re = tk.MustQuery("show causet t_regions regions")
  4614  	rows = re.Rows()
  4615  	// The index `idx` of causet t_regions should have 9 regions now.
  4616  	// 4 regions to causetstore record data.
  4617  	// 4 region to causetstore index idx data.
  4618  	// 1 region to causetstore index idx2 data.
  4619  	c.Assert(len(rows), Equals, 9)
  4620  	// Check the region start key.
  4621  	c.Assert(rows[0][1], Equals, fmt.Sprintf("t_%d_r", tbl.Meta().ID))
  4622  	c.Assert(rows[1][1], Equals, fmt.Sprintf("t_%d_r_-5000", tbl.Meta().ID))
  4623  	c.Assert(rows[2][1], Equals, fmt.Sprintf("t_%d_r_0", tbl.Meta().ID))
  4624  	c.Assert(rows[3][1], Equals, fmt.Sprintf("t_%d_r_5000", tbl.Meta().ID))
  4625  	c.Assert(rows[4][1], Matches, fmt.Sprintf("t_%d_", tbl.Meta().ID))
  4626  	c.Assert(rows[5][1], Matches, fmt.Sprintf("t_%d_i_1_.*", tbl.Meta().ID))
  4627  	c.Assert(rows[6][1], Matches, fmt.Sprintf("t_%d_i_1_.*", tbl.Meta().ID))
  4628  	c.Assert(rows[7][2], Equals, fmt.Sprintf("t_%d_i_2_", tbl.Meta().ID))
  4629  	c.Assert(rows[8][2], Equals, fmt.Sprintf("t_%d_r", tbl.Meta().ID))
  4630  
  4631  	// Test unsigned primary key and wait scatter finish.
  4632  	tk.MustInterDirc("drop causet if exists t_regions")
  4633  	atomic.StoreUint32(&dbs.EnableSplitBlockRegion, 1)
  4634  	tk.MustInterDirc("create causet t_regions (a int unsigned key, b int, index idx(b))")
  4635  
  4636  	// Test show causet regions.
  4637  	tk.MustInterDirc(`set @@stochastik.milevadb_wait_split_region_finish=1;`)
  4638  	tk.MustQuery(`split causet t_regions by (2500),(5000),(7500);`).Check(testkit.Rows("3 1"))
  4639  	re = tk.MustQuery("show causet t_regions regions")
  4640  	rows = re.Rows()
  4641  	// Block t_regions should have 4 regions now.
  4642  	c.Assert(len(rows), Equals, 4)
  4643  	tbl = testGetBlockByName(c, tk.Se, "test", "t_regions")
  4644  	// Check the region start key.
  4645  	c.Assert(rows[0][1], Matches, "t_.*")
  4646  	c.Assert(rows[1][1], Equals, fmt.Sprintf("t_%d_r_2500", tbl.Meta().ID))
  4647  	c.Assert(rows[2][1], Equals, fmt.Sprintf("t_%d_r_5000", tbl.Meta().ID))
  4648  	c.Assert(rows[3][1], Equals, fmt.Sprintf("t_%d_r_7500", tbl.Meta().ID))
  4649  
  4650  	// Test show causet index regions.
  4651  	tk.MustQuery(`split causet t_regions index idx by (250),(500),(750);`).Check(testkit.Rows("4 1"))
  4652  	re = tk.MustQuery("show causet t_regions index idx regions")
  4653  	rows = re.Rows()
  4654  	// The index `idx` of causet t_regions should have 4 regions now.
  4655  	c.Assert(len(rows), Equals, 4)
  4656  	// Check the region start key.
  4657  	c.Assert(rows[0][1], Equals, fmt.Sprintf("t_%d_", tbl.Meta().ID))
  4658  	c.Assert(rows[1][1], Matches, fmt.Sprintf("t_%d_i_1_.*", tbl.Meta().ID))
  4659  	c.Assert(rows[2][1], Matches, fmt.Sprintf("t_%d_i_1_.*", tbl.Meta().ID))
  4660  	c.Assert(rows[3][1], Matches, fmt.Sprintf("t_%d_i_1_.*", tbl.Meta().ID))
  4661  
  4662  	// Test show causet regions for partition causet when disable split region when create causet.
  4663  	atomic.StoreUint32(&dbs.EnableSplitBlockRegion, 0)
  4664  	tk.MustInterDirc("drop causet if exists partition_t;")
  4665  	tk.MustInterDirc("set @@stochastik.milevadb_enable_block_partition = '1';")
  4666  	tk.MustInterDirc("create causet partition_t (a int, b int,index(a)) partition by hash (a) partitions 3")
  4667  	re = tk.MustQuery("show causet partition_t regions")
  4668  	rows = re.Rows()
  4669  	c.Assert(len(rows), Equals, 1)
  4670  	c.Assert(rows[0][1], Matches, "t_.*")
  4671  
  4672  	// Test show causet regions for partition causet when enable split region when create causet.
  4673  	atomic.StoreUint32(&dbs.EnableSplitBlockRegion, 1)
  4674  	tk.MustInterDirc("set @@global.milevadb_scatter_region=1;")
  4675  	tk.MustInterDirc("drop causet if exists partition_t;")
  4676  	tk.MustInterDirc("create causet partition_t (a int, b int,index(a)) partition by hash (a) partitions 3")
  4677  	re = tk.MustQuery("show causet partition_t regions")
  4678  	rows = re.Rows()
  4679  	c.Assert(len(rows), Equals, 3)
  4680  	tbl = testGetBlockByName(c, tk.Se, "test", "partition_t")
  4681  	partitionDef := tbl.Meta().GetPartitionInfo().Definitions
  4682  	c.Assert(rows[0][1], Matches, fmt.Sprintf("t_%d_.*", partitionDef[0].ID))
  4683  	c.Assert(rows[1][1], Matches, fmt.Sprintf("t_%d_.*", partitionDef[1].ID))
  4684  	c.Assert(rows[2][1], Matches, fmt.Sprintf("t_%d_.*", partitionDef[2].ID))
  4685  
  4686  	// Test split partition region when add new partition.
  4687  	tk.MustInterDirc("drop causet if exists partition_t;")
  4688  	tk.MustInterDirc(`create causet partition_t (a int, b int,index(a)) PARTITION BY RANGE (a) (
  4689  		PARTITION p0 VALUES LESS THAN (10),
  4690  		PARTITION p1 VALUES LESS THAN (20),
  4691  		PARTITION p2 VALUES LESS THAN (30));`)
  4692  	tk.MustInterDirc(`alter causet partition_t add partition ( partition p3 values less than (40), partition p4 values less than (50) );`)
  4693  	re = tk.MustQuery("show causet partition_t regions")
  4694  	rows = re.Rows()
  4695  	c.Assert(len(rows), Equals, 5)
  4696  	tbl = testGetBlockByName(c, tk.Se, "test", "partition_t")
  4697  	partitionDef = tbl.Meta().GetPartitionInfo().Definitions
  4698  	c.Assert(rows[0][1], Matches, fmt.Sprintf("t_%d_.*", partitionDef[0].ID))
  4699  	c.Assert(rows[1][1], Matches, fmt.Sprintf("t_%d_.*", partitionDef[1].ID))
  4700  	c.Assert(rows[2][1], Matches, fmt.Sprintf("t_%d_.*", partitionDef[2].ID))
  4701  	c.Assert(rows[3][1], Matches, fmt.Sprintf("t_%d_.*", partitionDef[3].ID))
  4702  	c.Assert(rows[4][1], Matches, fmt.Sprintf("t_%d_.*", partitionDef[4].ID))
  4703  
  4704  	// Test pre-split causet region when create causet.
  4705  	tk.MustInterDirc("drop causet if exists t_pre")
  4706  	tk.MustInterDirc("create causet t_pre (a int, b int) shard_row_id_bits = 2 pre_split_regions=2;")
  4707  	re = tk.MustQuery("show causet t_pre regions")
  4708  	rows = re.Rows()
  4709  	// Block t_regions should have 4 regions now.
  4710  	c.Assert(len(rows), Equals, 4)
  4711  	tbl = testGetBlockByName(c, tk.Se, "test", "t_pre")
  4712  	c.Assert(rows[1][1], Equals, fmt.Sprintf("t_%d_r_2305843009213693952", tbl.Meta().ID))
  4713  	c.Assert(rows[2][1], Equals, fmt.Sprintf("t_%d_r_4611686018427387904", tbl.Meta().ID))
  4714  	c.Assert(rows[3][1], Equals, fmt.Sprintf("t_%d_r_6917529027641081856", tbl.Meta().ID))
  4715  
  4716  	// Test pre-split causet region when create causet.
  4717  	tk.MustInterDirc("drop causet if exists pt_pre")
  4718  	tk.MustInterDirc("create causet pt_pre (a int, b int) shard_row_id_bits = 2 pre_split_regions=2 partition by hash(a) partitions 3;")
  4719  	re = tk.MustQuery("show causet pt_pre regions")
  4720  	rows = re.Rows()
  4721  	// Block t_regions should have 4 regions now.
  4722  	c.Assert(len(rows), Equals, 12)
  4723  	tbl = testGetBlockByName(c, tk.Se, "test", "pt_pre")
  4724  	pi := tbl.Meta().GetPartitionInfo().Definitions
  4725  	c.Assert(len(pi), Equals, 3)
  4726  	for i, p := range pi {
  4727  		c.Assert(rows[1+4*i][1], Equals, fmt.Sprintf("t_%d_r_2305843009213693952", p.ID))
  4728  		c.Assert(rows[2+4*i][1], Equals, fmt.Sprintf("t_%d_r_4611686018427387904", p.ID))
  4729  		c.Assert(rows[3+4*i][1], Equals, fmt.Sprintf("t_%d_r_6917529027641081856", p.ID))
  4730  	}
  4731  
  4732  	defer atomic.StoreUint32(&dbs.EnableSplitBlockRegion, 0)
  4733  
  4734  	// Test split partition causet.
  4735  	tk.MustInterDirc("drop causet if exists t")
  4736  	tk.MustInterDirc("create causet t (a int,b int) partition by hash(a) partitions 5;")
  4737  	tk.MustQuery("split causet t between (0) and (4000000) regions 4;").Check(testkit.Rows("15 1"))
  4738  	re = tk.MustQuery("show causet t regions")
  4739  	rows = re.Rows()
  4740  	c.Assert(len(rows), Equals, 20)
  4741  	tbl = testGetBlockByName(c, tk.Se, "test", "t")
  4742  	c.Assert(len(tbl.Meta().GetPartitionInfo().Definitions), Equals, 5)
  4743  	for i, p := range tbl.Meta().GetPartitionInfo().Definitions {
  4744  		c.Assert(rows[i*4+0][1], Equals, fmt.Sprintf("t_%d_", p.ID))
  4745  		c.Assert(rows[i*4+1][1], Equals, fmt.Sprintf("t_%d_r_1000000", p.ID))
  4746  		c.Assert(rows[i*4+2][1], Equals, fmt.Sprintf("t_%d_r_2000000", p.ID))
  4747  		c.Assert(rows[i*4+3][1], Equals, fmt.Sprintf("t_%d_r_3000000", p.ID))
  4748  	}
  4749  
  4750  	// Test split region for partition causet with specified partition.
  4751  	tk.MustQuery("split causet t partition (p4) between (1000000) and (2000000) regions 5;").Check(testkit.Rows("4 1"))
  4752  	re = tk.MustQuery("show causet t regions")
  4753  	rows = re.Rows()
  4754  	c.Assert(len(rows), Equals, 24)
  4755  	tbl = testGetBlockByName(c, tk.Se, "test", "t")
  4756  	c.Assert(len(tbl.Meta().GetPartitionInfo().Definitions), Equals, 5)
  4757  	for i := 0; i < 4; i++ {
  4758  		p := tbl.Meta().GetPartitionInfo().Definitions[i]
  4759  		c.Assert(rows[i*4+0][1], Equals, fmt.Sprintf("t_%d_", p.ID))
  4760  		c.Assert(rows[i*4+1][1], Equals, fmt.Sprintf("t_%d_r_1000000", p.ID))
  4761  		c.Assert(rows[i*4+2][1], Equals, fmt.Sprintf("t_%d_r_2000000", p.ID))
  4762  		c.Assert(rows[i*4+3][1], Equals, fmt.Sprintf("t_%d_r_3000000", p.ID))
  4763  	}
  4764  	for i := 4; i < 5; i++ {
  4765  		p := tbl.Meta().GetPartitionInfo().Definitions[i]
  4766  		c.Assert(rows[i*4+0][1], Equals, fmt.Sprintf("t_%d_", p.ID))
  4767  		c.Assert(rows[i*4+1][1], Equals, fmt.Sprintf("t_%d_r_1000000", p.ID))
  4768  		c.Assert(rows[i*4+2][1], Equals, fmt.Sprintf("t_%d_r_1200000", p.ID))
  4769  		c.Assert(rows[i*4+3][1], Equals, fmt.Sprintf("t_%d_r_1400000", p.ID))
  4770  		c.Assert(rows[i*4+4][1], Equals, fmt.Sprintf("t_%d_r_1600000", p.ID))
  4771  		c.Assert(rows[i*4+5][1], Equals, fmt.Sprintf("t_%d_r_1800000", p.ID))
  4772  		c.Assert(rows[i*4+6][1], Equals, fmt.Sprintf("t_%d_r_2000000", p.ID))
  4773  		c.Assert(rows[i*4+7][1], Equals, fmt.Sprintf("t_%d_r_3000000", p.ID))
  4774  	}
  4775  
  4776  	// Test for show causet partition regions.
  4777  	for i := 0; i < 4; i++ {
  4778  		re = tk.MustQuery(fmt.Sprintf("show causet t partition (p%v) regions", i))
  4779  		rows = re.Rows()
  4780  		c.Assert(len(rows), Equals, 4)
  4781  		p := tbl.Meta().GetPartitionInfo().Definitions[i]
  4782  		c.Assert(rows[0][1], Equals, fmt.Sprintf("t_%d_", p.ID))
  4783  		c.Assert(rows[1][1], Equals, fmt.Sprintf("t_%d_r_1000000", p.ID))
  4784  		c.Assert(rows[2][1], Equals, fmt.Sprintf("t_%d_r_2000000", p.ID))
  4785  		c.Assert(rows[3][1], Equals, fmt.Sprintf("t_%d_r_3000000", p.ID))
  4786  	}
  4787  	re = tk.MustQuery("show causet t partition (p0, p4) regions")
  4788  	rows = re.Rows()
  4789  	c.Assert(len(rows), Equals, 12)
  4790  	p := tbl.Meta().GetPartitionInfo().Definitions[0]
  4791  	c.Assert(rows[0][1], Equals, fmt.Sprintf("t_%d_", p.ID))
  4792  	c.Assert(rows[1][1], Equals, fmt.Sprintf("t_%d_r_1000000", p.ID))
  4793  	c.Assert(rows[2][1], Equals, fmt.Sprintf("t_%d_r_2000000", p.ID))
  4794  	c.Assert(rows[3][1], Equals, fmt.Sprintf("t_%d_r_3000000", p.ID))
  4795  	p = tbl.Meta().GetPartitionInfo().Definitions[4]
  4796  	c.Assert(rows[4][1], Equals, fmt.Sprintf("t_%d_", p.ID))
  4797  	c.Assert(rows[5][1], Equals, fmt.Sprintf("t_%d_r_1000000", p.ID))
  4798  	c.Assert(rows[6][1], Equals, fmt.Sprintf("t_%d_r_1200000", p.ID))
  4799  	c.Assert(rows[7][1], Equals, fmt.Sprintf("t_%d_r_1400000", p.ID))
  4800  	c.Assert(rows[8][1], Equals, fmt.Sprintf("t_%d_r_1600000", p.ID))
  4801  	c.Assert(rows[9][1], Equals, fmt.Sprintf("t_%d_r_1800000", p.ID))
  4802  	c.Assert(rows[10][1], Equals, fmt.Sprintf("t_%d_r_2000000", p.ID))
  4803  	c.Assert(rows[11][1], Equals, fmt.Sprintf("t_%d_r_3000000", p.ID))
  4804  	// Test for duplicate partition names.
  4805  	re = tk.MustQuery("show causet t partition (p0, p0, p0) regions")
  4806  	rows = re.Rows()
  4807  	c.Assert(len(rows), Equals, 4)
  4808  	p = tbl.Meta().GetPartitionInfo().Definitions[0]
  4809  	c.Assert(rows[0][1], Equals, fmt.Sprintf("t_%d_", p.ID))
  4810  	c.Assert(rows[1][1], Equals, fmt.Sprintf("t_%d_r_1000000", p.ID))
  4811  	c.Assert(rows[2][1], Equals, fmt.Sprintf("t_%d_r_2000000", p.ID))
  4812  	c.Assert(rows[3][1], Equals, fmt.Sprintf("t_%d_r_3000000", p.ID))
  4813  
  4814  	// Test split partition causet index.
  4815  	tk.MustInterDirc("drop causet if exists t")
  4816  	tk.MustInterDirc("create causet t (a int,b int,index idx(a)) partition by hash(a) partitions 5;")
  4817  	tk.MustQuery("split causet t between (0) and (4000000) regions 4;").Check(testkit.Rows("20 1"))
  4818  	tk.MustQuery("split causet t index idx between (0) and (4000000) regions 4;").Check(testkit.Rows("20 1"))
  4819  	re = tk.MustQuery("show causet t regions")
  4820  	rows = re.Rows()
  4821  	c.Assert(len(rows), Equals, 40)
  4822  	tbl = testGetBlockByName(c, tk.Se, "test", "t")
  4823  	c.Assert(len(tbl.Meta().GetPartitionInfo().Definitions), Equals, 5)
  4824  	for i := 0; i < 5; i++ {
  4825  		p := tbl.Meta().GetPartitionInfo().Definitions[i]
  4826  		c.Assert(rows[i*8+0][1], Equals, fmt.Sprintf("t_%d_r", p.ID))
  4827  		c.Assert(rows[i*8+1][1], Equals, fmt.Sprintf("t_%d_r_1000000", p.ID))
  4828  		c.Assert(rows[i*8+2][1], Equals, fmt.Sprintf("t_%d_r_2000000", p.ID))
  4829  		c.Assert(rows[i*8+3][1], Equals, fmt.Sprintf("t_%d_r_3000000", p.ID))
  4830  		c.Assert(rows[i*8+4][1], Equals, fmt.Sprintf("t_%d_", p.ID))
  4831  		c.Assert(rows[i*8+5][1], Matches, fmt.Sprintf("t_%d_i_1_.*", p.ID))
  4832  		c.Assert(rows[i*8+6][1], Matches, fmt.Sprintf("t_%d_i_1_.*", p.ID))
  4833  		c.Assert(rows[i*8+7][1], Matches, fmt.Sprintf("t_%d_i_1_.*", p.ID))
  4834  	}
  4835  
  4836  	// Test split index region for partition causet with specified partition.
  4837  	tk.MustQuery("split causet t partition (p4) index idx between (0) and (1000000) regions 5;").Check(testkit.Rows("4 1"))
  4838  	re = tk.MustQuery("show causet t regions")
  4839  	rows = re.Rows()
  4840  	c.Assert(len(rows), Equals, 44)
  4841  	tbl = testGetBlockByName(c, tk.Se, "test", "t")
  4842  	c.Assert(len(tbl.Meta().GetPartitionInfo().Definitions), Equals, 5)
  4843  	for i := 0; i < 4; i++ {
  4844  		p := tbl.Meta().GetPartitionInfo().Definitions[i]
  4845  		c.Assert(rows[i*8+0][1], Equals, fmt.Sprintf("t_%d_r", p.ID))
  4846  		c.Assert(rows[i*8+1][1], Equals, fmt.Sprintf("t_%d_r_1000000", p.ID))
  4847  		c.Assert(rows[i*8+2][1], Equals, fmt.Sprintf("t_%d_r_2000000", p.ID))
  4848  		c.Assert(rows[i*8+3][1], Equals, fmt.Sprintf("t_%d_r_3000000", p.ID))
  4849  		c.Assert(rows[i*8+4][1], Equals, fmt.Sprintf("t_%d_", p.ID))
  4850  		c.Assert(rows[i*8+5][1], Matches, fmt.Sprintf("t_%d_i_1_.*", p.ID))
  4851  		c.Assert(rows[i*8+6][1], Matches, fmt.Sprintf("t_%d_i_1_.*", p.ID))
  4852  		c.Assert(rows[i*8+7][1], Matches, fmt.Sprintf("t_%d_i_1_.*", p.ID))
  4853  	}
  4854  	for i := 4; i < 5; i++ {
  4855  		p := tbl.Meta().GetPartitionInfo().Definitions[i]
  4856  		c.Assert(rows[i*8+0][1], Equals, fmt.Sprintf("t_%d_r", p.ID))
  4857  		c.Assert(rows[i*8+1][1], Equals, fmt.Sprintf("t_%d_r_1000000", p.ID))
  4858  		c.Assert(rows[i*8+2][1], Equals, fmt.Sprintf("t_%d_r_2000000", p.ID))
  4859  		c.Assert(rows[i*8+3][1], Equals, fmt.Sprintf("t_%d_r_3000000", p.ID))
  4860  		c.Assert(rows[i*8+4][1], Equals, fmt.Sprintf("t_%d_", p.ID))
  4861  		c.Assert(rows[i*8+5][1], Matches, fmt.Sprintf("t_%d_i_1_.*", p.ID))
  4862  		c.Assert(rows[i*8+6][1], Matches, fmt.Sprintf("t_%d_i_1_.*", p.ID))
  4863  		c.Assert(rows[i*8+7][1], Matches, fmt.Sprintf("t_%d_i_1_.*", p.ID))
  4864  		c.Assert(rows[i*8+8][1], Matches, fmt.Sprintf("t_%d_i_1_.*", p.ID))
  4865  		c.Assert(rows[i*8+9][1], Matches, fmt.Sprintf("t_%d_i_1_.*", p.ID))
  4866  		c.Assert(rows[i*8+10][1], Matches, fmt.Sprintf("t_%d_i_1_.*", p.ID))
  4867  		c.Assert(rows[i*8+11][1], Matches, fmt.Sprintf("t_%d_i_1_.*", p.ID))
  4868  	}
  4869  
  4870  	// Test show causet partition region on unknown-partition.
  4871  	err = tk.QueryToErr("show causet t partition (p_unknown) index idx regions")
  4872  	c.Assert(terror.ErrorEqual(err, causet.ErrUnknownPartition), IsTrue)
  4873  
  4874  	// Test show causet partition index.
  4875  	for i := 0; i < 4; i++ {
  4876  		re = tk.MustQuery(fmt.Sprintf("show causet t partition (p%v) index idx regions", i))
  4877  		rows = re.Rows()
  4878  		c.Assert(len(rows), Equals, 4)
  4879  		p := tbl.Meta().GetPartitionInfo().Definitions[i]
  4880  		c.Assert(rows[0][1], Equals, fmt.Sprintf("t_%d_", p.ID))
  4881  		c.Assert(rows[1][1], Matches, fmt.Sprintf("t_%d_i_1_.*", p.ID))
  4882  		c.Assert(rows[2][1], Matches, fmt.Sprintf("t_%d_i_1_.*", p.ID))
  4883  		c.Assert(rows[3][1], Matches, fmt.Sprintf("t_%d_i_1_.*", p.ID))
  4884  	}
  4885  	re = tk.MustQuery("show causet t partition (p3,p4) index idx regions")
  4886  	rows = re.Rows()
  4887  	c.Assert(len(rows), Equals, 12)
  4888  	p = tbl.Meta().GetPartitionInfo().Definitions[3]
  4889  	c.Assert(rows[0][1], Equals, fmt.Sprintf("t_%d_", p.ID))
  4890  	c.Assert(rows[1][1], Matches, fmt.Sprintf("t_%d_i_1_.*", p.ID))
  4891  	c.Assert(rows[2][1], Matches, fmt.Sprintf("t_%d_i_1_.*", p.ID))
  4892  	c.Assert(rows[3][1], Matches, fmt.Sprintf("t_%d_i_1_.*", p.ID))
  4893  	p = tbl.Meta().GetPartitionInfo().Definitions[4]
  4894  	c.Assert(rows[4][1], Equals, fmt.Sprintf("t_%d_", p.ID))
  4895  	c.Assert(rows[5][1], Matches, fmt.Sprintf("t_%d_i_1_.*", p.ID))
  4896  	c.Assert(rows[6][1], Matches, fmt.Sprintf("t_%d_i_1_.*", p.ID))
  4897  	c.Assert(rows[7][1], Matches, fmt.Sprintf("t_%d_i_1_.*", p.ID))
  4898  	c.Assert(rows[8][1], Matches, fmt.Sprintf("t_%d_i_1_.*", p.ID))
  4899  	c.Assert(rows[9][1], Matches, fmt.Sprintf("t_%d_i_1_.*", p.ID))
  4900  	c.Assert(rows[10][1], Matches, fmt.Sprintf("t_%d_i_1_.*", p.ID))
  4901  	c.Assert(rows[11][1], Matches, fmt.Sprintf("t_%d_i_1_.*", p.ID))
  4902  
  4903  	// Test split for the second index.
  4904  	tk.MustInterDirc("drop causet if exists t")
  4905  	tk.MustInterDirc("create causet t (a int,b int,index idx(a), index idx2(b))")
  4906  	tk.MustQuery("split causet t index idx2 between (0) and (4000000) regions 2;").Check(testkit.Rows("3 1"))
  4907  	re = tk.MustQuery("show causet t regions")
  4908  	rows = re.Rows()
  4909  	c.Assert(len(rows), Equals, 4)
  4910  	tbl = testGetBlockByName(c, tk.Se, "test", "t")
  4911  	c.Assert(rows[0][1], Equals, fmt.Sprintf("t_%d_i_3_", tbl.Meta().ID))
  4912  	c.Assert(rows[1][1], Equals, fmt.Sprintf("t_%d_", tbl.Meta().ID))
  4913  	c.Assert(rows[2][1], Matches, fmt.Sprintf("t_%d_i_2_.*", tbl.Meta().ID))
  4914  	c.Assert(rows[3][1], Matches, fmt.Sprintf("t_%d_i_2_.*", tbl.Meta().ID))
  4915  
  4916  	// Test show causet partition region on non-partition causet.
  4917  	err = tk.QueryToErr("show causet t partition (p3,p4) index idx regions")
  4918  	c.Assert(terror.ErrorEqual(err, causetembedded.ErrPartitionClauseOnNonpartitioned), IsTrue)
  4919  }
  4920  
  4921  func testGetBlockByName(c *C, ctx stochastikctx.Context, EDB, causet string) causet.Block {
  4922  	dom := petri.GetPetri(ctx)
  4923  	// Make sure the causet schemaReplicant is the new schemaReplicant.
  4924  	err := dom.Reload()
  4925  	c.Assert(err, IsNil)
  4926  	tbl, err := dom.SchemaReplicant().BlockByName(perceptron.NewCIStr(EDB), perceptron.NewCIStr(causet))
  4927  	c.Assert(err, IsNil)
  4928  	return tbl
  4929  }
  4930  
  4931  func (s *testSuiteP2) TestIssue10435(c *C) {
  4932  	tk := testkit.NewTestKit(c, s.causetstore)
  4933  	tk.MustInterDirc("use test")
  4934  	tk.MustInterDirc("drop causet if exists t1")
  4935  	tk.MustInterDirc("create causet t1(i int, j int, k int)")
  4936  	tk.MustInterDirc("insert into t1 VALUES (1,1,1),(2,2,2),(3,3,3),(4,4,4)")
  4937  	tk.MustInterDirc("INSERT INTO t1 SELECT 10*i,j,5*j FROM t1 UNION SELECT 20*i,j,5*j FROM t1 UNION SELECT 30*i,j,5*j FROM t1")
  4938  
  4939  	tk.MustInterDirc("set @@stochastik.milevadb_enable_window_function=1")
  4940  	tk.MustQuery("SELECT SUM(i) OVER W FROM t1 WINDOW w AS (PARTITION BY j ORDER BY i) ORDER BY 1+SUM(i) OVER w").Check(
  4941  		testkit.Rows("1", "2", "3", "4", "11", "22", "31", "33", "44", "61", "62", "93", "122", "124", "183", "244"),
  4942  	)
  4943  }
  4944  
  4945  func (s *testSuiteP2) TestUnsignedFeedback(c *C) {
  4946  	tk := testkit.NewTestKit(c, s.causetstore)
  4947  	oriProbability := statistics.FeedbackProbability.Load()
  4948  	statistics.FeedbackProbability.CausetStore(1.0)
  4949  	defer func() { statistics.FeedbackProbability.CausetStore(oriProbability) }()
  4950  	tk.MustInterDirc("use test")
  4951  	tk.MustInterDirc("drop causet if exists t")
  4952  	tk.MustInterDirc("create causet t(a bigint unsigned, b int, primary key(a))")
  4953  	tk.MustInterDirc("insert into t values (1,1),(2,2)")
  4954  	tk.MustInterDirc("analyze causet t")
  4955  	tk.MustQuery("select count(distinct b) from t").Check(testkit.Rows("2"))
  4956  	result := tk.MustQuery("explain analyze select count(distinct b) from t")
  4957  	c.Assert(result.Rows()[2][4], Equals, "causet:t")
  4958  	c.Assert(result.Rows()[2][6], Equals, "range:[0,+inf], keep order:false")
  4959  }
  4960  
  4961  func (s *testSuite) TestOOMPanicCausetAction(c *C) {
  4962  	tk := testkit.NewTestKit(c, s.causetstore)
  4963  	tk.MustInterDirc("use test")
  4964  	tk.MustInterDirc("drop causet if exists t")
  4965  	tk.MustInterDirc("create causet t (a int primary key, b double);")
  4966  	tk.MustInterDirc("insert into t values (1,1)")
  4967  	sm := &mockStochastikManager1{
  4968  		PS: make([]*soliton.ProcessInfo, 0),
  4969  	}
  4970  	tk.Se.SetStochastikManager(sm)
  4971  	s.petri.ExpensiveQueryHandle().SetStochastikManager(sm)
  4972  	defer config.RestoreFunc()()
  4973  	config.UFIDelateGlobal(func(conf *config.Config) {
  4974  		conf.OOMCausetAction = config.OOMCausetActionCancel
  4975  	})
  4976  	tk.MustInterDirc("set @@milevadb_mem_quota_query=1;")
  4977  	err := tk.QueryToErr("select sum(b) from t group by a;")
  4978  	c.Assert(err, NotNil)
  4979  	c.Assert(err.Error(), Matches, "Out Of Memory Quota!.*")
  4980  
  4981  	// Test insert from select oom panic.
  4982  	tk.MustInterDirc("drop causet if exists t,t1")
  4983  	tk.MustInterDirc("create causet t (a bigint);")
  4984  	tk.MustInterDirc("create causet t1 (a bigint);")
  4985  	tk.MustInterDirc("set @@milevadb_mem_quota_query=200;")
  4986  	_, err = tk.InterDirc("insert into t1 values (1),(2),(3),(4),(5);")
  4987  	c.Assert(err.Error(), Matches, "Out Of Memory Quota!.*")
  4988  	_, err = tk.InterDirc("replace into t1 values (1),(2),(3),(4),(5);")
  4989  	c.Assert(err.Error(), Matches, "Out Of Memory Quota!.*")
  4990  	tk.MustInterDirc("set @@milevadb_mem_quota_query=10000")
  4991  	tk.MustInterDirc("insert into t1 values (1),(2),(3),(4),(5);")
  4992  	tk.MustInterDirc("set @@milevadb_mem_quota_query=10;")
  4993  	_, err = tk.InterDirc("insert into t select a from t1 order by a desc;")
  4994  	c.Assert(err.Error(), Matches, "Out Of Memory Quota!.*")
  4995  	_, err = tk.InterDirc("replace into t select a from t1 order by a desc;")
  4996  	c.Assert(err.Error(), Matches, "Out Of Memory Quota!.*")
  4997  
  4998  	tk.MustInterDirc("set @@milevadb_mem_quota_query=10000")
  4999  	tk.MustInterDirc("insert into t values (1),(2),(3),(4),(5);")
  5000  	// Set the memory quota to 244 to make this ALLEGROALLEGROSQL panic during the DeleteInterDirc
  5001  	// instead of the BlockReaderInterDirc.
  5002  	tk.MustInterDirc("set @@milevadb_mem_quota_query=244;")
  5003  	_, err = tk.InterDirc("delete from t")
  5004  	c.Assert(err.Error(), Matches, "Out Of Memory Quota!.*")
  5005  
  5006  	tk.MustInterDirc("set @@milevadb_mem_quota_query=10000;")
  5007  	tk.MustInterDirc("delete from t1")
  5008  	tk.MustInterDirc("insert into t1 values(1)")
  5009  	tk.MustInterDirc("insert into t values (1),(2),(3),(4),(5);")
  5010  	tk.MustInterDirc("set @@milevadb_mem_quota_query=244;")
  5011  	_, err = tk.InterDirc("delete t, t1 from t join t1 on t.a = t1.a")
  5012  
  5013  	tk.MustInterDirc("set @@milevadb_mem_quota_query=100000;")
  5014  	tk.MustInterDirc("truncate causet t")
  5015  	tk.MustInterDirc("insert into t values(1),(2),(3)")
  5016  	// set the memory to quota to make the ALLEGROALLEGROSQL panic during UFIDelateInterDirc instead
  5017  	// of BlockReader.
  5018  	tk.MustInterDirc("set @@milevadb_mem_quota_query=244;")
  5019  	_, err = tk.InterDirc("uFIDelate t set a = 4")
  5020  	c.Assert(err.Error(), Matches, "Out Of Memory Quota!.*")
  5021  }
  5022  
  5023  type testRecoverBlock struct {
  5024  	causetstore ekv.CausetStorage
  5025  	dom         *petri.Petri
  5026  	cluster     cluster.Cluster
  5027  	cli         *regionProperityClient
  5028  }
  5029  
  5030  func (s *testRecoverBlock) SetUpSuite(c *C) {
  5031  	cli := &regionProperityClient{}
  5032  	hijackClient := func(c einsteindb.Client) einsteindb.Client {
  5033  		cli.Client = c
  5034  		return cli
  5035  	}
  5036  	s.cli = cli
  5037  
  5038  	var err error
  5039  	s.causetstore, err = mockstore.NewMockStore(
  5040  		mockstore.WithClientHijacker(hijackClient),
  5041  		mockstore.WithClusterInspector(func(c cluster.Cluster) {
  5042  			mockstore.BootstrapWithSingleStore(c)
  5043  			s.cluster = c
  5044  		}),
  5045  	)
  5046  	c.Assert(err, IsNil)
  5047  	s.dom, err = stochastik.BootstrapStochastik(s.causetstore)
  5048  	c.Assert(err, IsNil)
  5049  }
  5050  
  5051  func (s *testRecoverBlock) TearDownSuite(c *C) {
  5052  	s.causetstore.Close()
  5053  	s.dom.Close()
  5054  }
  5055  
  5056  func (s *testRecoverBlock) TestRecoverBlock(c *C) {
  5057  	c.Assert(failpoint.Enable("github.com/whtcorpsinc/milevadb/spacetime/autoid/mockAutoIDChange", `return(true)`), IsNil)
  5058  	defer func() {
  5059  		failpoint.Disable("github.com/whtcorpsinc/milevadb/spacetime/autoid/mockAutoIDChange")
  5060  	}()
  5061  	tk := testkit.NewTestKit(c, s.causetstore)
  5062  	tk.MustInterDirc("create database if not exists test_recover")
  5063  	tk.MustInterDirc("use test_recover")
  5064  	tk.MustInterDirc("drop causet if exists t_recover")
  5065  	tk.MustInterDirc("create causet t_recover (a int);")
  5066  	defer func(originGC bool) {
  5067  		if originGC {
  5068  			dbs.EmulatorGCEnable()
  5069  		} else {
  5070  			dbs.EmulatorGCDisable()
  5071  		}
  5072  	}(dbs.IsEmulatorGCEnable())
  5073  
  5074  	// disable emulator GC.
  5075  	// Otherwise emulator GC will delete causet record as soon as possible after execute drop causet dbs.
  5076  	dbs.EmulatorGCDisable()
  5077  	gcTimeFormat := "20060102-15:04:05 -0700 MST"
  5078  	timeBeforeDrop := time.Now().Add(0 - 48*60*60*time.Second).Format(gcTimeFormat)
  5079  	timeAfterDrop := time.Now().Add(48 * 60 * 60 * time.Second).Format(gcTimeFormat)
  5080  	safePointALLEGROSQL := `INSERT HIGH_PRIORITY INTO allegrosql.milevadb VALUES ('einsteindb_gc_safe_point', '%[1]s', '')
  5081  			       ON DUPLICATE KEY
  5082  			       UFIDelATE variable_value = '%[1]s'`
  5083  	// clear GC variables first.
  5084  	tk.MustInterDirc("delete from allegrosql.milevadb where variable_name in ( 'einsteindb_gc_safe_point','einsteindb_gc_enable' )")
  5085  
  5086  	tk.MustInterDirc("insert into t_recover values (1),(2),(3)")
  5087  	tk.MustInterDirc("drop causet t_recover")
  5088  
  5089  	// if GC safe point is not exists in allegrosql.milevadb
  5090  	_, err := tk.InterDirc("recover causet t_recover")
  5091  	c.Assert(err, NotNil)
  5092  	c.Assert(err.Error(), Equals, "can not get 'einsteindb_gc_safe_point'")
  5093  	// set GC safe point
  5094  	tk.MustInterDirc(fmt.Sprintf(safePointALLEGROSQL, timeBeforeDrop))
  5095  
  5096  	// if GC enable is not exists in allegrosql.milevadb
  5097  	_, err = tk.InterDirc("recover causet t_recover")
  5098  	c.Assert(err, NotNil)
  5099  	c.Assert(err.Error(), Equals, "[dbs:-1]can not get 'einsteindb_gc_enable'")
  5100  
  5101  	err = gcutil.EnableGC(tk.Se)
  5102  	c.Assert(err, IsNil)
  5103  
  5104  	// recover job is before GC safe point
  5105  	tk.MustInterDirc(fmt.Sprintf(safePointALLEGROSQL, timeAfterDrop))
  5106  	_, err = tk.InterDirc("recover causet t_recover")
  5107  	c.Assert(err, NotNil)
  5108  	c.Assert(strings.Contains(err.Error(), "Can't find dropped/truncated causet 't_recover' in GC safe point"), Equals, true)
  5109  
  5110  	// set GC safe point
  5111  	tk.MustInterDirc(fmt.Sprintf(safePointALLEGROSQL, timeBeforeDrop))
  5112  	// if there is a new causet with the same name, should return failed.
  5113  	tk.MustInterDirc("create causet t_recover (a int);")
  5114  	_, err = tk.InterDirc("recover causet t_recover")
  5115  	c.Assert(err.Error(), Equals, schemareplicant.ErrBlockExists.GenWithStackByArgs("t_recover").Error())
  5116  
  5117  	// drop the new causet with the same name, then recover causet.
  5118  	tk.MustInterDirc("rename causet t_recover to t_recover2")
  5119  
  5120  	// do recover causet.
  5121  	tk.MustInterDirc("recover causet t_recover")
  5122  
  5123  	// check recover causet spacetime and data record.
  5124  	tk.MustQuery("select * from t_recover;").Check(testkit.Rows("1", "2", "3"))
  5125  	// check recover causet autoID.
  5126  	tk.MustInterDirc("insert into t_recover values (4),(5),(6)")
  5127  	tk.MustQuery("select * from t_recover;").Check(testkit.Rows("1", "2", "3", "4", "5", "6"))
  5128  	// check rebase auto id.
  5129  	tk.MustQuery("select a,_milevadb_rowid from t_recover;").Check(testkit.Rows("1 1", "2 2", "3 3", "4 5001", "5 5002", "6 5003"))
  5130  
  5131  	// recover causet by none exits job.
  5132  	_, err = tk.InterDirc(fmt.Sprintf("recover causet by job %d", 10000000))
  5133  	c.Assert(err, NotNil)
  5134  
  5135  	// Disable GC by manual first, then after recover causet, the GC enable status should also be disabled.
  5136  	err = gcutil.DisableGC(tk.Se)
  5137  	c.Assert(err, IsNil)
  5138  
  5139  	tk.MustInterDirc("delete from t_recover where a > 1")
  5140  	tk.MustInterDirc("drop causet t_recover")
  5141  
  5142  	tk.MustInterDirc("recover causet t_recover")
  5143  
  5144  	// check recover causet spacetime and data record.
  5145  	tk.MustQuery("select * from t_recover;").Check(testkit.Rows("1"))
  5146  	// check recover causet autoID.
  5147  	tk.MustInterDirc("insert into t_recover values (7),(8),(9)")
  5148  	tk.MustQuery("select * from t_recover;").Check(testkit.Rows("1", "7", "8", "9"))
  5149  
  5150  	// Recover truncate causet.
  5151  	tk.MustInterDirc("truncate causet t_recover")
  5152  	tk.MustInterDirc("rename causet t_recover to t_recover_new")
  5153  	tk.MustInterDirc("recover causet t_recover")
  5154  	tk.MustInterDirc("insert into t_recover values (10)")
  5155  	tk.MustQuery("select * from t_recover;").Check(testkit.Rows("1", "7", "8", "9", "10"))
  5156  
  5157  	// Test for recover one causet multiple time.
  5158  	tk.MustInterDirc("drop causet t_recover")
  5159  	tk.MustInterDirc("flashback causet t_recover to t_recover_tmp")
  5160  	_, err = tk.InterDirc(fmt.Sprintf("recover causet t_recover"))
  5161  	c.Assert(schemareplicant.ErrBlockExists.Equal(err), IsTrue)
  5162  
  5163  	gcEnable, err := gcutil.CheckGCEnable(tk.Se)
  5164  	c.Assert(err, IsNil)
  5165  	c.Assert(gcEnable, Equals, false)
  5166  }
  5167  
  5168  func (s *testRecoverBlock) TestFlashbackBlock(c *C) {
  5169  	c.Assert(failpoint.Enable("github.com/whtcorpsinc/milevadb/spacetime/autoid/mockAutoIDChange", `return(true)`), IsNil)
  5170  	defer func() {
  5171  		c.Assert(failpoint.Disable("github.com/whtcorpsinc/milevadb/spacetime/autoid/mockAutoIDChange"), IsNil)
  5172  	}()
  5173  	tk := testkit.NewTestKit(c, s.causetstore)
  5174  	tk.MustInterDirc("create database if not exists test_flashback")
  5175  	tk.MustInterDirc("use test_flashback")
  5176  	tk.MustInterDirc("drop causet if exists t_flashback")
  5177  	tk.MustInterDirc("create causet t_flashback (a int);")
  5178  	defer func(originGC bool) {
  5179  		if originGC {
  5180  			dbs.EmulatorGCEnable()
  5181  		} else {
  5182  			dbs.EmulatorGCDisable()
  5183  		}
  5184  	}(dbs.IsEmulatorGCEnable())
  5185  
  5186  	// Disable emulator GC.
  5187  	// Otherwise emulator GC will delete causet record as soon as possible after execute drop causet dbs.
  5188  	dbs.EmulatorGCDisable()
  5189  	gcTimeFormat := "20060102-15:04:05 -0700 MST"
  5190  	timeBeforeDrop := time.Now().Add(0 - 48*60*60*time.Second).Format(gcTimeFormat)
  5191  	safePointALLEGROSQL := `INSERT HIGH_PRIORITY INTO allegrosql.milevadb VALUES ('einsteindb_gc_safe_point', '%[1]s', '')
  5192  			       ON DUPLICATE KEY
  5193  			       UFIDelATE variable_value = '%[1]s'`
  5194  	// Clear GC variables first.
  5195  	tk.MustInterDirc("delete from allegrosql.milevadb where variable_name in ( 'einsteindb_gc_safe_point','einsteindb_gc_enable' )")
  5196  	// Set GC safe point
  5197  	tk.MustInterDirc(fmt.Sprintf(safePointALLEGROSQL, timeBeforeDrop))
  5198  	// Set GC enable.
  5199  	err := gcutil.EnableGC(tk.Se)
  5200  	c.Assert(err, IsNil)
  5201  
  5202  	tk.MustInterDirc("insert into t_flashback values (1),(2),(3)")
  5203  	tk.MustInterDirc("drop causet t_flashback")
  5204  
  5205  	// Test flash causet with not_exist_block_name name.
  5206  	_, err = tk.InterDirc("flashback causet t_not_exists")
  5207  	c.Assert(err.Error(), Equals, "Can't find dropped/truncated causet: t_not_exists in DBS history jobs")
  5208  
  5209  	// Test flashback causet failed by there is already a new causet with the same name.
  5210  	// If there is a new causet with the same name, should return failed.
  5211  	tk.MustInterDirc("create causet t_flashback (a int);")
  5212  	_, err = tk.InterDirc("flashback causet t_flashback")
  5213  	c.Assert(err.Error(), Equals, schemareplicant.ErrBlockExists.GenWithStackByArgs("t_flashback").Error())
  5214  
  5215  	// Drop the new causet with the same name, then flashback causet.
  5216  	tk.MustInterDirc("rename causet t_flashback to t_flashback_tmp")
  5217  
  5218  	// Test for flashback causet.
  5219  	tk.MustInterDirc("flashback causet t_flashback")
  5220  	// Check flashback causet spacetime and data record.
  5221  	tk.MustQuery("select * from t_flashback;").Check(testkit.Rows("1", "2", "3"))
  5222  	// Check flashback causet autoID.
  5223  	tk.MustInterDirc("insert into t_flashback values (4),(5),(6)")
  5224  	tk.MustQuery("select * from t_flashback;").Check(testkit.Rows("1", "2", "3", "4", "5", "6"))
  5225  	// Check rebase auto id.
  5226  	tk.MustQuery("select a,_milevadb_rowid from t_flashback;").Check(testkit.Rows("1 1", "2 2", "3 3", "4 5001", "5 5002", "6 5003"))
  5227  
  5228  	// Test for flashback to new causet.
  5229  	tk.MustInterDirc("drop causet t_flashback")
  5230  	tk.MustInterDirc("create causet t_flashback (a int);")
  5231  	tk.MustInterDirc("flashback causet t_flashback to t_flashback2")
  5232  	// Check flashback causet spacetime and data record.
  5233  	tk.MustQuery("select * from t_flashback2;").Check(testkit.Rows("1", "2", "3", "4", "5", "6"))
  5234  	// Check flashback causet autoID.
  5235  	tk.MustInterDirc("insert into t_flashback2 values (7),(8),(9)")
  5236  	tk.MustQuery("select * from t_flashback2;").Check(testkit.Rows("1", "2", "3", "4", "5", "6", "7", "8", "9"))
  5237  	// Check rebase auto id.
  5238  	tk.MustQuery("select a,_milevadb_rowid from t_flashback2;").Check(testkit.Rows("1 1", "2 2", "3 3", "4 5001", "5 5002", "6 5003", "7 10001", "8 10002", "9 10003"))
  5239  
  5240  	// Test for flashback one causet multiple time.
  5241  	_, err = tk.InterDirc(fmt.Sprintf("flashback causet t_flashback to t_flashback4"))
  5242  	c.Assert(schemareplicant.ErrBlockExists.Equal(err), IsTrue)
  5243  
  5244  	// Test for flashback truncated causet to new causet.
  5245  	tk.MustInterDirc("truncate causet t_flashback2")
  5246  	tk.MustInterDirc("flashback causet t_flashback2 to t_flashback3")
  5247  	// Check flashback causet spacetime and data record.
  5248  	tk.MustQuery("select * from t_flashback3;").Check(testkit.Rows("1", "2", "3", "4", "5", "6", "7", "8", "9"))
  5249  	// Check flashback causet autoID.
  5250  	tk.MustInterDirc("insert into t_flashback3 values (10),(11)")
  5251  	tk.MustQuery("select * from t_flashback3;").Check(testkit.Rows("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11"))
  5252  	// Check rebase auto id.
  5253  	tk.MustQuery("select a,_milevadb_rowid from t_flashback3;").Check(testkit.Rows("1 1", "2 2", "3 3", "4 5001", "5 5002", "6 5003", "7 10001", "8 10002", "9 10003", "10 15001", "11 15002"))
  5254  
  5255  	// Test for flashback drop partition causet.
  5256  	tk.MustInterDirc("drop causet if exists t_p_flashback")
  5257  	tk.MustInterDirc("create causet t_p_flashback (a int) partition by hash(a) partitions 4;")
  5258  	tk.MustInterDirc("insert into t_p_flashback values (1),(2),(3)")
  5259  	tk.MustInterDirc("drop causet t_p_flashback")
  5260  	tk.MustInterDirc("flashback causet t_p_flashback")
  5261  	// Check flashback causet spacetime and data record.
  5262  	tk.MustQuery("select * from t_p_flashback order by a;").Check(testkit.Rows("1", "2", "3"))
  5263  	// Check flashback causet autoID.
  5264  	tk.MustInterDirc("insert into t_p_flashback values (4),(5)")
  5265  	tk.MustQuery("select a,_milevadb_rowid from t_p_flashback order by a;").Check(testkit.Rows("1 1", "2 2", "3 3", "4 5001", "5 5002"))
  5266  
  5267  	// Test for flashback truncate partition causet.
  5268  	tk.MustInterDirc("truncate causet t_p_flashback")
  5269  	tk.MustInterDirc("flashback causet t_p_flashback to t_p_flashback1")
  5270  	// Check flashback causet spacetime and data record.
  5271  	tk.MustQuery("select * from t_p_flashback1 order by a;").Check(testkit.Rows("1", "2", "3", "4", "5"))
  5272  	// Check flashback causet autoID.
  5273  	tk.MustInterDirc("insert into t_p_flashback1 values (6)")
  5274  	tk.MustQuery("select a,_milevadb_rowid from t_p_flashback1 order by a;").Check(testkit.Rows("1 1", "2 2", "3 3", "4 5001", "5 5002", "6 10001"))
  5275  
  5276  	tk.MustInterDirc("drop database if exists Test2")
  5277  	tk.MustInterDirc("create database Test2")
  5278  	tk.MustInterDirc("use Test2")
  5279  	tk.MustInterDirc("create causet t (a int);")
  5280  	tk.MustInterDirc("insert into t values (1),(2)")
  5281  	tk.MustInterDirc("drop causet t")
  5282  	tk.MustInterDirc("flashback causet t")
  5283  	tk.MustQuery("select a from t order by a").Check(testkit.Rows("1", "2"))
  5284  
  5285  	tk.MustInterDirc("drop causet t")
  5286  	tk.MustInterDirc("drop database if exists Test3")
  5287  	tk.MustInterDirc("create database Test3")
  5288  	tk.MustInterDirc("use Test3")
  5289  	tk.MustInterDirc("create causet t (a int);")
  5290  	tk.MustInterDirc("drop causet t")
  5291  	tk.MustInterDirc("drop database Test3")
  5292  	tk.MustInterDirc("use Test2")
  5293  	tk.MustInterDirc("flashback causet t")
  5294  	tk.MustInterDirc("insert into t values (3)")
  5295  	tk.MustQuery("select a from t order by a").Check(testkit.Rows("1", "2", "3"))
  5296  }
  5297  
  5298  func (s *testSuiteP2) TestPointGetPreparedCauset(c *C) {
  5299  	tk1 := testkit.NewTestKit(c, s.causetstore)
  5300  	tk1.MustInterDirc("drop database if exists ps_text")
  5301  	defer tk1.MustInterDirc("drop database if exists ps_text")
  5302  	tk1.MustInterDirc("create database ps_text")
  5303  	tk1.MustInterDirc("use ps_text")
  5304  
  5305  	tk1.MustInterDirc(`create causet t (a int, b int, c int,
  5306  			primary key k_a(a),
  5307  			unique key k_b(b))`)
  5308  	tk1.MustInterDirc("insert into t values (1, 1, 1)")
  5309  	tk1.MustInterDirc("insert into t values (2, 2, 2)")
  5310  	tk1.MustInterDirc("insert into t values (3, 3, 3)")
  5311  
  5312  	pspk1Id, _, _, err := tk1.Se.PrepareStmt("select * from t where a = ?")
  5313  	c.Assert(err, IsNil)
  5314  	tk1.Se.GetStochastikVars().PreparedStmts[pspk1Id].(*causetembedded.CachedPrepareStmt).PreparedAst.UseCache = false
  5315  	pspk2Id, _, _, err := tk1.Se.PrepareStmt("select * from t where ? = a ")
  5316  	c.Assert(err, IsNil)
  5317  	tk1.Se.GetStochastikVars().PreparedStmts[pspk2Id].(*causetembedded.CachedPrepareStmt).PreparedAst.UseCache = false
  5318  
  5319  	ctx := context.Background()
  5320  	// first time plan generated
  5321  	rs, err := tk1.Se.InterDircutePreparedStmt(ctx, pspk1Id, []types.Causet{types.NewCauset(0)})
  5322  	c.Assert(err, IsNil)
  5323  	tk1.ResultSetToResult(rs, Commentf("%v", rs)).Check(nil)
  5324  
  5325  	// using the generated plan but with different params
  5326  	rs, err = tk1.Se.InterDircutePreparedStmt(ctx, pspk1Id, []types.Causet{types.NewCauset(1)})
  5327  	c.Assert(err, IsNil)
  5328  	tk1.ResultSetToResult(rs, Commentf("%v", rs)).Check(testkit.Rows("1 1 1"))
  5329  
  5330  	rs, err = tk1.Se.InterDircutePreparedStmt(ctx, pspk1Id, []types.Causet{types.NewCauset(2)})
  5331  	c.Assert(err, IsNil)
  5332  	tk1.ResultSetToResult(rs, Commentf("%v", rs)).Check(testkit.Rows("2 2 2"))
  5333  
  5334  	rs, err = tk1.Se.InterDircutePreparedStmt(ctx, pspk2Id, []types.Causet{types.NewCauset(3)})
  5335  	c.Assert(err, IsNil)
  5336  	tk1.ResultSetToResult(rs, Commentf("%v", rs)).Check(testkit.Rows("3 3 3"))
  5337  
  5338  	rs, err = tk1.Se.InterDircutePreparedStmt(ctx, pspk2Id, []types.Causet{types.NewCauset(0)})
  5339  	c.Assert(err, IsNil)
  5340  	tk1.ResultSetToResult(rs, Commentf("%v", rs)).Check(nil)
  5341  
  5342  	rs, err = tk1.Se.InterDircutePreparedStmt(ctx, pspk2Id, []types.Causet{types.NewCauset(1)})
  5343  	c.Assert(err, IsNil)
  5344  	tk1.ResultSetToResult(rs, Commentf("%v", rs)).Check(testkit.Rows("1 1 1"))
  5345  
  5346  	rs, err = tk1.Se.InterDircutePreparedStmt(ctx, pspk2Id, []types.Causet{types.NewCauset(2)})
  5347  	c.Assert(err, IsNil)
  5348  	tk1.ResultSetToResult(rs, Commentf("%v", rs)).Check(testkit.Rows("2 2 2"))
  5349  
  5350  	rs, err = tk1.Se.InterDircutePreparedStmt(ctx, pspk2Id, []types.Causet{types.NewCauset(3)})
  5351  	c.Assert(err, IsNil)
  5352  	tk1.ResultSetToResult(rs, Commentf("%v", rs)).Check(testkit.Rows("3 3 3"))
  5353  
  5354  	// unique index
  5355  	psuk1Id, _, _, err := tk1.Se.PrepareStmt("select * from t where b = ? ")
  5356  	c.Assert(err, IsNil)
  5357  	tk1.Se.GetStochastikVars().PreparedStmts[psuk1Id].(*causetembedded.CachedPrepareStmt).PreparedAst.UseCache = false
  5358  
  5359  	rs, err = tk1.Se.InterDircutePreparedStmt(ctx, psuk1Id, []types.Causet{types.NewCauset(1)})
  5360  	c.Assert(err, IsNil)
  5361  	tk1.ResultSetToResult(rs, Commentf("%v", rs)).Check(testkit.Rows("1 1 1"))
  5362  
  5363  	rs, err = tk1.Se.InterDircutePreparedStmt(ctx, psuk1Id, []types.Causet{types.NewCauset(2)})
  5364  	c.Assert(err, IsNil)
  5365  	tk1.ResultSetToResult(rs, Commentf("%v", rs)).Check(testkit.Rows("2 2 2"))
  5366  
  5367  	rs, err = tk1.Se.InterDircutePreparedStmt(ctx, psuk1Id, []types.Causet{types.NewCauset(3)})
  5368  	c.Assert(err, IsNil)
  5369  	tk1.ResultSetToResult(rs, Commentf("%v", rs)).Check(testkit.Rows("3 3 3"))
  5370  
  5371  	rs, err = tk1.Se.InterDircutePreparedStmt(ctx, psuk1Id, []types.Causet{types.NewCauset(0)})
  5372  	c.Assert(err, IsNil)
  5373  	tk1.ResultSetToResult(rs, Commentf("%v", rs)).Check(nil)
  5374  
  5375  	// test schemaReplicant changed, cached plan should be invalidated
  5376  	tk1.MustInterDirc("alter causet t add defCausumn defCaus4 int default 10 after c")
  5377  	rs, err = tk1.Se.InterDircutePreparedStmt(ctx, pspk1Id, []types.Causet{types.NewCauset(0)})
  5378  	c.Assert(err, IsNil)
  5379  	tk1.ResultSetToResult(rs, Commentf("%v", rs)).Check(nil)
  5380  
  5381  	rs, err = tk1.Se.InterDircutePreparedStmt(ctx, pspk1Id, []types.Causet{types.NewCauset(1)})
  5382  	c.Assert(err, IsNil)
  5383  	tk1.ResultSetToResult(rs, Commentf("%v", rs)).Check(testkit.Rows("1 1 1 10"))
  5384  
  5385  	rs, err = tk1.Se.InterDircutePreparedStmt(ctx, pspk1Id, []types.Causet{types.NewCauset(2)})
  5386  	c.Assert(err, IsNil)
  5387  	tk1.ResultSetToResult(rs, Commentf("%v", rs)).Check(testkit.Rows("2 2 2 10"))
  5388  
  5389  	rs, err = tk1.Se.InterDircutePreparedStmt(ctx, pspk2Id, []types.Causet{types.NewCauset(3)})
  5390  	c.Assert(err, IsNil)
  5391  	tk1.ResultSetToResult(rs, Commentf("%v", rs)).Check(testkit.Rows("3 3 3 10"))
  5392  
  5393  	tk1.MustInterDirc("alter causet t drop index k_b")
  5394  	rs, err = tk1.Se.InterDircutePreparedStmt(ctx, psuk1Id, []types.Causet{types.NewCauset(1)})
  5395  	c.Assert(err, IsNil)
  5396  	tk1.ResultSetToResult(rs, Commentf("%v", rs)).Check(testkit.Rows("1 1 1 10"))
  5397  
  5398  	rs, err = tk1.Se.InterDircutePreparedStmt(ctx, psuk1Id, []types.Causet{types.NewCauset(2)})
  5399  	c.Assert(err, IsNil)
  5400  	tk1.ResultSetToResult(rs, Commentf("%v", rs)).Check(testkit.Rows("2 2 2 10"))
  5401  
  5402  	rs, err = tk1.Se.InterDircutePreparedStmt(ctx, psuk1Id, []types.Causet{types.NewCauset(3)})
  5403  	c.Assert(err, IsNil)
  5404  	tk1.ResultSetToResult(rs, Commentf("%v", rs)).Check(testkit.Rows("3 3 3 10"))
  5405  
  5406  	rs, err = tk1.Se.InterDircutePreparedStmt(ctx, psuk1Id, []types.Causet{types.NewCauset(0)})
  5407  	c.Assert(err, IsNil)
  5408  	tk1.ResultSetToResult(rs, Commentf("%v", rs)).Check(nil)
  5409  
  5410  	tk1.MustInterDirc(`insert into t values(4, 3, 3, 11)`)
  5411  	rs, err = tk1.Se.InterDircutePreparedStmt(ctx, psuk1Id, []types.Causet{types.NewCauset(1)})
  5412  	c.Assert(err, IsNil)
  5413  	tk1.ResultSetToResult(rs, Commentf("%v", rs)).Check(testkit.Rows("1 1 1 10"))
  5414  
  5415  	rs, err = tk1.Se.InterDircutePreparedStmt(ctx, psuk1Id, []types.Causet{types.NewCauset(2)})
  5416  	c.Assert(err, IsNil)
  5417  	tk1.ResultSetToResult(rs, Commentf("%v", rs)).Check(testkit.Rows("2 2 2 10"))
  5418  
  5419  	rs, err = tk1.Se.InterDircutePreparedStmt(ctx, psuk1Id, []types.Causet{types.NewCauset(3)})
  5420  	c.Assert(err, IsNil)
  5421  	tk1.ResultSetToResult(rs, Commentf("%v", rs)).Check(testkit.Rows("3 3 3 10", "4 3 3 11"))
  5422  
  5423  	rs, err = tk1.Se.InterDircutePreparedStmt(ctx, psuk1Id, []types.Causet{types.NewCauset(0)})
  5424  	c.Assert(err, IsNil)
  5425  	tk1.ResultSetToResult(rs, Commentf("%v", rs)).Check(nil)
  5426  
  5427  	tk1.MustInterDirc("delete from t where a = 4")
  5428  	tk1.MustInterDirc("alter causet t add index k_b(b)")
  5429  	rs, err = tk1.Se.InterDircutePreparedStmt(ctx, psuk1Id, []types.Causet{types.NewCauset(1)})
  5430  	c.Assert(err, IsNil)
  5431  	tk1.ResultSetToResult(rs, Commentf("%v", rs)).Check(testkit.Rows("1 1 1 10"))
  5432  
  5433  	rs, err = tk1.Se.InterDircutePreparedStmt(ctx, psuk1Id, []types.Causet{types.NewCauset(2)})
  5434  	c.Assert(err, IsNil)
  5435  	tk1.ResultSetToResult(rs, Commentf("%v", rs)).Check(testkit.Rows("2 2 2 10"))
  5436  
  5437  	rs, err = tk1.Se.InterDircutePreparedStmt(ctx, psuk1Id, []types.Causet{types.NewCauset(3)})
  5438  	c.Assert(err, IsNil)
  5439  	tk1.ResultSetToResult(rs, Commentf("%v", rs)).Check(testkit.Rows("3 3 3 10"))
  5440  
  5441  	rs, err = tk1.Se.InterDircutePreparedStmt(ctx, psuk1Id, []types.Causet{types.NewCauset(0)})
  5442  	c.Assert(err, IsNil)
  5443  	tk1.ResultSetToResult(rs, Commentf("%v", rs)).Check(nil)
  5444  
  5445  	// use pk again
  5446  	rs, err = tk1.Se.InterDircutePreparedStmt(ctx, pspk2Id, []types.Causet{types.NewCauset(3)})
  5447  	c.Assert(err, IsNil)
  5448  	tk1.ResultSetToResult(rs, Commentf("%v", rs)).Check(testkit.Rows("3 3 3 10"))
  5449  
  5450  	rs, err = tk1.Se.InterDircutePreparedStmt(ctx, pspk1Id, []types.Causet{types.NewCauset(3)})
  5451  	c.Assert(err, IsNil)
  5452  	tk1.ResultSetToResult(rs, Commentf("%v", rs)).Check(testkit.Rows("3 3 3 10"))
  5453  }
  5454  
  5455  func (s *testSuiteP2) TestPointGetPreparedCausetWithCommitMode(c *C) {
  5456  	tk1 := testkit.NewTestKit(c, s.causetstore)
  5457  	tk1.MustInterDirc("drop database if exists ps_text")
  5458  	defer tk1.MustInterDirc("drop database if exists ps_text")
  5459  	tk1.MustInterDirc("create database ps_text")
  5460  	tk1.MustInterDirc("use ps_text")
  5461  
  5462  	tk1.MustInterDirc(`create causet t (a int, b int, c int,
  5463  			primary key k_a(a),
  5464  			unique key k_b(b))`)
  5465  	tk1.MustInterDirc("insert into t values (1, 1, 1)")
  5466  	tk1.MustInterDirc("insert into t values (2, 2, 2)")
  5467  	tk1.MustInterDirc("insert into t values (3, 3, 3)")
  5468  
  5469  	pspk1Id, _, _, err := tk1.Se.PrepareStmt("select * from t where a = ?")
  5470  	c.Assert(err, IsNil)
  5471  	tk1.Se.GetStochastikVars().PreparedStmts[pspk1Id].(*causetembedded.CachedPrepareStmt).PreparedAst.UseCache = false
  5472  
  5473  	ctx := context.Background()
  5474  	// first time plan generated
  5475  	rs, err := tk1.Se.InterDircutePreparedStmt(ctx, pspk1Id, []types.Causet{types.NewCauset(0)})
  5476  	c.Assert(err, IsNil)
  5477  	tk1.ResultSetToResult(rs, Commentf("%v", rs)).Check(nil)
  5478  
  5479  	// using the generated plan but with different params
  5480  	rs, err = tk1.Se.InterDircutePreparedStmt(ctx, pspk1Id, []types.Causet{types.NewCauset(1)})
  5481  	c.Assert(err, IsNil)
  5482  	tk1.ResultSetToResult(rs, Commentf("%v", rs)).Check(testkit.Rows("1 1 1"))
  5483  
  5484  	// next start a non autocommit txn
  5485  	tk1.MustInterDirc("set autocommit = 0")
  5486  	tk1.MustInterDirc("begin")
  5487  	// try to exec using point get plan(this plan should not go short path)
  5488  	rs, err = tk1.Se.InterDircutePreparedStmt(ctx, pspk1Id, []types.Causet{types.NewCauset(1)})
  5489  	c.Assert(err, IsNil)
  5490  	tk1.ResultSetToResult(rs, Commentf("%v", rs)).Check(testkit.Rows("1 1 1"))
  5491  
  5492  	// uFIDelate rows
  5493  	tk2 := testkit.NewTestKit(c, s.causetstore)
  5494  	tk2.MustInterDirc("use ps_text")
  5495  	tk2.MustInterDirc("uFIDelate t set c = c + 10 where c = 1")
  5496  
  5497  	// try to point get again
  5498  	rs, err = tk1.Se.InterDircutePreparedStmt(ctx, pspk1Id, []types.Causet{types.NewCauset(1)})
  5499  	c.Assert(err, IsNil)
  5500  	tk1.ResultSetToResult(rs, Commentf("%v", rs)).Check(testkit.Rows("1 1 1"))
  5501  
  5502  	// try to uFIDelate in stochastik 1
  5503  	tk1.MustInterDirc("uFIDelate t set c = c + 10 where c = 1")
  5504  	_, err = tk1.InterDirc("commit")
  5505  	c.Assert(ekv.ErrWriteConflict.Equal(err), IsTrue, Commentf("error: %s", err))
  5506  
  5507  	// verify
  5508  	rs, err = tk1.Se.InterDircutePreparedStmt(ctx, pspk1Id, []types.Causet{types.NewCauset(1)})
  5509  	c.Assert(err, IsNil)
  5510  	tk1.ResultSetToResult(rs, Commentf("%v", rs)).Check(testkit.Rows("1 1 11"))
  5511  
  5512  	rs, err = tk1.Se.InterDircutePreparedStmt(ctx, pspk1Id, []types.Causet{types.NewCauset(2)})
  5513  	c.Assert(err, IsNil)
  5514  	tk1.ResultSetToResult(rs, Commentf("%v", rs)).Check(testkit.Rows("2 2 2"))
  5515  
  5516  	tk2.MustQuery("select * from t where a = 1").Check(testkit.Rows("1 1 11"))
  5517  }
  5518  
  5519  func (s *testSuiteP2) TestPointUFIDelatePreparedCauset(c *C) {
  5520  	tk1 := testkit.NewTestKit(c, s.causetstore)
  5521  	tk1.MustInterDirc("drop database if exists pu_test")
  5522  	defer tk1.MustInterDirc("drop database if exists pu_test")
  5523  	tk1.MustInterDirc("create database pu_test")
  5524  	tk1.MustInterDirc("use pu_test")
  5525  
  5526  	tk1.MustInterDirc(`create causet t (a int, b int, c int,
  5527  			primary key k_a(a),
  5528  			unique key k_b(b))`)
  5529  	tk1.MustInterDirc("insert into t values (1, 1, 1)")
  5530  	tk1.MustInterDirc("insert into t values (2, 2, 2)")
  5531  	tk1.MustInterDirc("insert into t values (3, 3, 3)")
  5532  
  5533  	uFIDelateID1, pc, _, err := tk1.Se.PrepareStmt(`uFIDelate t set c = c + 1 where a = ?`)
  5534  	c.Assert(err, IsNil)
  5535  	tk1.Se.GetStochastikVars().PreparedStmts[uFIDelateID1].(*causetembedded.CachedPrepareStmt).PreparedAst.UseCache = false
  5536  	c.Assert(pc, Equals, 1)
  5537  	uFIDelateID2, pc, _, err := tk1.Se.PrepareStmt(`uFIDelate t set c = c + 2 where ? = a`)
  5538  	c.Assert(err, IsNil)
  5539  	tk1.Se.GetStochastikVars().PreparedStmts[uFIDelateID2].(*causetembedded.CachedPrepareStmt).PreparedAst.UseCache = false
  5540  	c.Assert(pc, Equals, 1)
  5541  
  5542  	ctx := context.Background()
  5543  	// first time plan generated
  5544  	rs, err := tk1.Se.InterDircutePreparedStmt(ctx, uFIDelateID1, []types.Causet{types.NewCauset(3)})
  5545  	c.Assert(rs, IsNil)
  5546  	c.Assert(err, IsNil)
  5547  	tk1.MustQuery("select * from t where a = 3").Check(testkit.Rows("3 3 4"))
  5548  
  5549  	// using the generated plan but with different params
  5550  	rs, err = tk1.Se.InterDircutePreparedStmt(ctx, uFIDelateID1, []types.Causet{types.NewCauset(3)})
  5551  	c.Assert(rs, IsNil)
  5552  	c.Assert(err, IsNil)
  5553  	tk1.MustQuery("select * from t where a = 3").Check(testkit.Rows("3 3 5"))
  5554  
  5555  	rs, err = tk1.Se.InterDircutePreparedStmt(ctx, uFIDelateID1, []types.Causet{types.NewCauset(3)})
  5556  	c.Assert(rs, IsNil)
  5557  	c.Assert(err, IsNil)
  5558  	tk1.MustQuery("select * from t where a = 3").Check(testkit.Rows("3 3 6"))
  5559  
  5560  	// uFIDelateID2
  5561  	rs, err = tk1.Se.InterDircutePreparedStmt(ctx, uFIDelateID2, []types.Causet{types.NewCauset(3)})
  5562  	c.Assert(rs, IsNil)
  5563  	c.Assert(err, IsNil)
  5564  	tk1.MustQuery("select * from t where a = 3").Check(testkit.Rows("3 3 8"))
  5565  
  5566  	rs, err = tk1.Se.InterDircutePreparedStmt(ctx, uFIDelateID2, []types.Causet{types.NewCauset(3)})
  5567  	c.Assert(rs, IsNil)
  5568  	c.Assert(err, IsNil)
  5569  	tk1.MustQuery("select * from t where a = 3").Check(testkit.Rows("3 3 10"))
  5570  
  5571  	// unique index
  5572  	uFIDelUkID1, _, _, err := tk1.Se.PrepareStmt(`uFIDelate t set c = c + 10 where b = ?`)
  5573  	c.Assert(err, IsNil)
  5574  	tk1.Se.GetStochastikVars().PreparedStmts[uFIDelUkID1].(*causetembedded.CachedPrepareStmt).PreparedAst.UseCache = false
  5575  	rs, err = tk1.Se.InterDircutePreparedStmt(ctx, uFIDelUkID1, []types.Causet{types.NewCauset(3)})
  5576  	c.Assert(rs, IsNil)
  5577  	c.Assert(err, IsNil)
  5578  	tk1.MustQuery("select * from t where a = 3").Check(testkit.Rows("3 3 20"))
  5579  
  5580  	rs, err = tk1.Se.InterDircutePreparedStmt(ctx, uFIDelUkID1, []types.Causet{types.NewCauset(3)})
  5581  	c.Assert(rs, IsNil)
  5582  	c.Assert(err, IsNil)
  5583  	tk1.MustQuery("select * from t where a = 3").Check(testkit.Rows("3 3 30"))
  5584  
  5585  	// test schemaReplicant changed, cached plan should be invalidated
  5586  	tk1.MustInterDirc("alter causet t add defCausumn defCaus4 int default 10 after c")
  5587  	rs, err = tk1.Se.InterDircutePreparedStmt(ctx, uFIDelateID1, []types.Causet{types.NewCauset(3)})
  5588  	c.Assert(rs, IsNil)
  5589  	c.Assert(err, IsNil)
  5590  	tk1.MustQuery("select * from t where a = 3").Check(testkit.Rows("3 3 31 10"))
  5591  
  5592  	rs, err = tk1.Se.InterDircutePreparedStmt(ctx, uFIDelateID1, []types.Causet{types.NewCauset(3)})
  5593  	c.Assert(rs, IsNil)
  5594  	c.Assert(err, IsNil)
  5595  	tk1.MustQuery("select * from t where a = 3").Check(testkit.Rows("3 3 32 10"))
  5596  
  5597  	tk1.MustInterDirc("alter causet t drop index k_b")
  5598  	rs, err = tk1.Se.InterDircutePreparedStmt(ctx, uFIDelUkID1, []types.Causet{types.NewCauset(3)})
  5599  	c.Assert(rs, IsNil)
  5600  	c.Assert(err, IsNil)
  5601  	tk1.MustQuery("select * from t where a = 3").Check(testkit.Rows("3 3 42 10"))
  5602  
  5603  	rs, err = tk1.Se.InterDircutePreparedStmt(ctx, uFIDelUkID1, []types.Causet{types.NewCauset(3)})
  5604  	c.Assert(rs, IsNil)
  5605  	c.Assert(err, IsNil)
  5606  	tk1.MustQuery("select * from t where a = 3").Check(testkit.Rows("3 3 52 10"))
  5607  
  5608  	tk1.MustInterDirc("alter causet t add unique index k_b(b)")
  5609  	rs, err = tk1.Se.InterDircutePreparedStmt(ctx, uFIDelUkID1, []types.Causet{types.NewCauset(3)})
  5610  	c.Assert(rs, IsNil)
  5611  	c.Assert(err, IsNil)
  5612  	tk1.MustQuery("select * from t where a = 3").Check(testkit.Rows("3 3 62 10"))
  5613  
  5614  	rs, err = tk1.Se.InterDircutePreparedStmt(ctx, uFIDelUkID1, []types.Causet{types.NewCauset(3)})
  5615  	c.Assert(rs, IsNil)
  5616  	c.Assert(err, IsNil)
  5617  	tk1.MustQuery("select * from t where a = 3").Check(testkit.Rows("3 3 72 10"))
  5618  
  5619  	tk1.MustQuery("select * from t where a = 1").Check(testkit.Rows("1 1 1 10"))
  5620  	tk1.MustQuery("select * from t where a = 2").Check(testkit.Rows("2 2 2 10"))
  5621  }
  5622  
  5623  func (s *testSuiteP2) TestPointUFIDelatePreparedCausetWithCommitMode(c *C) {
  5624  	tk1 := testkit.NewTestKit(c, s.causetstore)
  5625  	tk1.MustInterDirc("drop database if exists pu_test2")
  5626  	defer tk1.MustInterDirc("drop database if exists pu_test2")
  5627  	tk1.MustInterDirc("create database pu_test2")
  5628  	tk1.MustInterDirc("use pu_test2")
  5629  
  5630  	tk1.MustInterDirc(`create causet t (a int, b int, c int,
  5631  			primary key k_a(a),
  5632  			unique key k_b(b))`)
  5633  	tk1.MustInterDirc("insert into t values (1, 1, 1)")
  5634  	tk1.MustInterDirc("insert into t values (2, 2, 2)")
  5635  	tk1.MustInterDirc("insert into t values (3, 3, 3)")
  5636  
  5637  	ctx := context.Background()
  5638  	uFIDelateID1, _, _, err := tk1.Se.PrepareStmt(`uFIDelate t set c = c + 1 where a = ?`)
  5639  	tk1.Se.GetStochastikVars().PreparedStmts[uFIDelateID1].(*causetembedded.CachedPrepareStmt).PreparedAst.UseCache = false
  5640  	c.Assert(err, IsNil)
  5641  
  5642  	// first time plan generated
  5643  	rs, err := tk1.Se.InterDircutePreparedStmt(ctx, uFIDelateID1, []types.Causet{types.NewCauset(3)})
  5644  	c.Assert(rs, IsNil)
  5645  	c.Assert(err, IsNil)
  5646  	tk1.MustQuery("select * from t where a = 3").Check(testkit.Rows("3 3 4"))
  5647  
  5648  	rs, err = tk1.Se.InterDircutePreparedStmt(ctx, uFIDelateID1, []types.Causet{types.NewCauset(3)})
  5649  	c.Assert(rs, IsNil)
  5650  	c.Assert(err, IsNil)
  5651  	tk1.MustQuery("select * from t where a = 3").Check(testkit.Rows("3 3 5"))
  5652  
  5653  	// next start a non autocommit txn
  5654  	tk1.MustInterDirc("set autocommit = 0")
  5655  	tk1.MustInterDirc("begin")
  5656  	// try to exec using point get plan(this plan should not go short path)
  5657  	rs, err = tk1.Se.InterDircutePreparedStmt(ctx, uFIDelateID1, []types.Causet{types.NewCauset(3)})
  5658  	c.Assert(rs, IsNil)
  5659  	c.Assert(err, IsNil)
  5660  	tk1.MustQuery("select * from t where a = 3").Check(testkit.Rows("3 3 6"))
  5661  
  5662  	// uFIDelate rows
  5663  	tk2 := testkit.NewTestKit(c, s.causetstore)
  5664  	tk2.MustInterDirc("use pu_test2")
  5665  	tk2.MustInterDirc(`prepare pu2 from "uFIDelate t set c = c + 2 where ? = a "`)
  5666  	tk2.MustInterDirc("set @p3 = 3")
  5667  	tk2.MustQuery("select * from t where a = 3").Check(testkit.Rows("3 3 5"))
  5668  	tk2.MustInterDirc("execute pu2 using @p3")
  5669  	tk2.MustQuery("select * from t where a = 3").Check(testkit.Rows("3 3 7"))
  5670  	tk2.MustInterDirc("execute pu2 using @p3")
  5671  	tk2.MustQuery("select * from t where a = 3").Check(testkit.Rows("3 3 9"))
  5672  
  5673  	// try to uFIDelate in stochastik 1
  5674  	tk1.MustQuery("select * from t where a = 3").Check(testkit.Rows("3 3 6"))
  5675  	_, err = tk1.InterDirc("commit")
  5676  	c.Assert(ekv.ErrWriteConflict.Equal(err), IsTrue, Commentf("error: %s", err))
  5677  
  5678  	// verify
  5679  	tk2.MustQuery("select * from t where a = 1").Check(testkit.Rows("1 1 1"))
  5680  	tk1.MustQuery("select * from t where a = 2").Check(testkit.Rows("2 2 2"))
  5681  	tk2.MustQuery("select * from t where a = 3").Check(testkit.Rows("3 3 9"))
  5682  	tk1.MustQuery("select * from t where a = 2").Check(testkit.Rows("2 2 2"))
  5683  	tk1.MustQuery("select * from t where a = 3").Check(testkit.Rows("3 3 9"))
  5684  
  5685  	// again next start a non autocommit txn
  5686  	tk1.MustInterDirc("set autocommit = 0")
  5687  	tk1.MustInterDirc("begin")
  5688  	rs, err = tk1.Se.InterDircutePreparedStmt(ctx, uFIDelateID1, []types.Causet{types.NewCauset(3)})
  5689  	c.Assert(rs, IsNil)
  5690  	c.Assert(err, IsNil)
  5691  	tk1.MustQuery("select * from t where a = 3").Check(testkit.Rows("3 3 10"))
  5692  
  5693  	rs, err = tk1.Se.InterDircutePreparedStmt(ctx, uFIDelateID1, []types.Causet{types.NewCauset(3)})
  5694  	c.Assert(rs, IsNil)
  5695  	c.Assert(err, IsNil)
  5696  	tk1.MustQuery("select * from t where a = 3").Check(testkit.Rows("3 3 11"))
  5697  	tk1.MustInterDirc("commit")
  5698  
  5699  	tk2.MustQuery("select * from t where a = 3").Check(testkit.Rows("3 3 11"))
  5700  }
  5701  
  5702  func (s *testSuite1) TestPartitionHashCode(c *C) {
  5703  	tk := testkit.NewTestKitWithInit(c, s.causetstore)
  5704  	tk.MustInterDirc(`create causet t(c1 bigint, c2 bigint, c3 bigint, primary key(c1))
  5705  			      partition by hash (c1) partitions 4;`)
  5706  	wg := sync.WaitGroup{}
  5707  	for i := 0; i < 5; i++ {
  5708  		wg.Add(1)
  5709  		go func() {
  5710  			defer wg.Done()
  5711  			tk1 := testkit.NewTestKitWithInit(c, s.causetstore)
  5712  			for i := 0; i < 5; i++ {
  5713  				tk1.MustInterDirc("select * from t")
  5714  			}
  5715  		}()
  5716  	}
  5717  	wg.Wait()
  5718  }
  5719  
  5720  func (s *testSuite1) TestAlterDefaultValue(c *C) {
  5721  	tk := testkit.NewTestKit(c, s.causetstore)
  5722  	tk.MustInterDirc("use test")
  5723  	tk.MustInterDirc("drop causet if exists t1")
  5724  	tk.MustInterDirc("create causet t(a int, primary key(a))")
  5725  	tk.MustInterDirc("insert into t(a) values(1)")
  5726  	tk.MustInterDirc("alter causet t add defCausumn b int default 1")
  5727  	tk.MustInterDirc("alter causet t alter b set default 2")
  5728  	tk.MustQuery("select b from t where a = 1").Check(testkit.Rows("1"))
  5729  }
  5730  
  5731  type testClusterBlockSuite struct {
  5732  	testSuiteWithCliBase
  5733  	rpcserver  *grpc.Server
  5734  	listenAddr string
  5735  }
  5736  
  5737  func (s *testClusterBlockSuite) SetUpSuite(c *C) {
  5738  	s.testSuiteWithCliBase.SetUpSuite(c)
  5739  	s.rpcserver, s.listenAddr = s.setUpRPCService(c, "127.0.0.1:0")
  5740  }
  5741  
  5742  func (s *testClusterBlockSuite) setUpRPCService(c *C, addr string) (*grpc.Server, string) {
  5743  	sm := &mockStochastikManager1{}
  5744  	sm.PS = append(sm.PS, &soliton.ProcessInfo{
  5745  		ID:      1,
  5746  		User:    "root",
  5747  		Host:    "127.0.0.1",
  5748  		Command: allegrosql.ComQuery,
  5749  	})
  5750  	lis, err := net.Listen("tcp", addr)
  5751  	c.Assert(err, IsNil)
  5752  	srv := server.NewRPCServer(config.GetGlobalConfig(), s.dom, sm)
  5753  	port := lis.Addr().(*net.TCPAddr).Port
  5754  	addr = fmt.Sprintf("127.0.0.1:%d", port)
  5755  	go func() {
  5756  		err = srv.Serve(lis)
  5757  		c.Assert(err, IsNil)
  5758  	}()
  5759  	config.UFIDelateGlobal(func(conf *config.Config) {
  5760  		conf.Status.StatusPort = uint(port)
  5761  	})
  5762  	return srv, addr
  5763  }
  5764  func (s *testClusterBlockSuite) TearDownSuite(c *C) {
  5765  	if s.rpcserver != nil {
  5766  		s.rpcserver.Stop()
  5767  		s.rpcserver = nil
  5768  	}
  5769  	s.testSuiteWithCliBase.TearDownSuite(c)
  5770  }
  5771  
  5772  func (s *testClusterBlockSuite) TestSlowQuery(c *C) {
  5773  	writeFile := func(file string, data string) {
  5774  		f, err := os.OpenFile(file, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644)
  5775  		c.Assert(err, IsNil)
  5776  		_, err = f.Write([]byte(data))
  5777  		c.Assert(f.Close(), IsNil)
  5778  		c.Assert(err, IsNil)
  5779  	}
  5780  
  5781  	logData0 := ""
  5782  	logData1 := `
  5783  # Time: 2020-02-15T18:00:01.000000+08:00
  5784  select 1;
  5785  # Time: 2020-02-15T19:00:05.000000+08:00
  5786  select 2;`
  5787  	logData2 := `
  5788  # Time: 2020-02-16T18:00:01.000000+08:00
  5789  select 3;
  5790  # Time: 2020-02-16T18:00:05.000000+08:00
  5791  select 4;`
  5792  	logData3 := `
  5793  # Time: 2020-02-16T19:00:00.000000+08:00
  5794  select 5;
  5795  # Time: 2020-02-17T18:00:05.000000+08:00
  5796  select 6;`
  5797  	logData4 := `
  5798  # Time: 2020-05-14T19:03:54.314615176+08:00
  5799  select 7;`
  5800  
  5801  	fileName0 := "milevadb-slow-2020-02-14T19-04-05.01.log"
  5802  	fileName1 := "milevadb-slow-2020-02-15T19-04-05.01.log"
  5803  	fileName2 := "milevadb-slow-2020-02-16T19-04-05.01.log"
  5804  	fileName3 := "milevadb-slow-2020-02-17T18-00-05.01.log"
  5805  	fileName4 := "milevadb-slow.log"
  5806  	writeFile(fileName0, logData0)
  5807  	writeFile(fileName1, logData1)
  5808  	writeFile(fileName2, logData2)
  5809  	writeFile(fileName3, logData3)
  5810  	writeFile(fileName4, logData4)
  5811  	defer func() {
  5812  		os.Remove(fileName0)
  5813  		os.Remove(fileName1)
  5814  		os.Remove(fileName2)
  5815  		os.Remove(fileName3)
  5816  		os.Remove(fileName4)
  5817  	}()
  5818  	tk := testkit.NewTestKitWithInit(c, s.causetstore)
  5819  	loc, err := time.LoadLocation("Asia/Shanghai")
  5820  	c.Assert(err, IsNil)
  5821  	tk.Se.GetStochastikVars().TimeZone = loc
  5822  	tk.MustInterDirc("use information_schema")
  5823  	cases := []struct {
  5824  		prepareALLEGROSQL string
  5825  		allegrosql        string
  5826  		result            []string
  5827  	}{
  5828  		{
  5829  			allegrosql: "select count(*),min(time),max(time) from %s where time > '2020-01-26 21:51:00' and time < now()",
  5830  			result:     []string{"7|2020-02-15 18:00:01.000000|2020-05-14 19:03:54.314615"},
  5831  		},
  5832  		{
  5833  			allegrosql: "select count(*),min(time),max(time) from %s where time > '2020-02-15 19:00:00' and time < '2020-02-16 18:00:02'",
  5834  			result:     []string{"2|2020-02-15 19:00:05.000000|2020-02-16 18:00:01.000000"},
  5835  		},
  5836  		{
  5837  			allegrosql: "select count(*),min(time),max(time) from %s where time > '2020-02-16 18:00:02' and time < '2020-02-17 17:00:00'",
  5838  			result:     []string{"2|2020-02-16 18:00:05.000000|2020-02-16 19:00:00.000000"},
  5839  		},
  5840  		{
  5841  			allegrosql: "select count(*),min(time),max(time) from %s where time > '2020-02-16 18:00:02' and time < '2020-02-17 20:00:00'",
  5842  			result:     []string{"3|2020-02-16 18:00:05.000000|2020-02-17 18:00:05.000000"},
  5843  		},
  5844  		{
  5845  			allegrosql: "select count(*),min(time),max(time) from %s",
  5846  			result:     []string{"1|2020-05-14 19:03:54.314615|2020-05-14 19:03:54.314615"},
  5847  		},
  5848  		{
  5849  			allegrosql: "select count(*),min(time) from %s where time > '2020-02-16 20:00:00'",
  5850  			result:     []string{"1|2020-02-17 18:00:05.000000"},
  5851  		},
  5852  		{
  5853  			allegrosql: "select count(*) from %s where time > '2020-02-17 20:00:00'",
  5854  			result:     []string{"0"},
  5855  		},
  5856  		{
  5857  			allegrosql: "select query from %s where time > '2020-01-26 21:51:00' and time < now()",
  5858  			result:     []string{"select 1;", "select 2;", "select 3;", "select 4;", "select 5;", "select 6;", "select 7;"},
  5859  		},
  5860  		// Test for different timezone.
  5861  		{
  5862  			prepareALLEGROSQL: "set @@time_zone = '+00:00'",
  5863  			allegrosql:        "select time from %s where time = '2020-02-17 10:00:05.000000'",
  5864  			result:            []string{"2020-02-17 10:00:05.000000"},
  5865  		},
  5866  		{
  5867  			prepareALLEGROSQL: "set @@time_zone = '+02:00'",
  5868  			allegrosql:        "select time from %s where time = '2020-02-17 12:00:05.000000'",
  5869  			result:            []string{"2020-02-17 12:00:05.000000"},
  5870  		},
  5871  		// Test for issue 17224
  5872  		{
  5873  			prepareALLEGROSQL: "set @@time_zone = '+08:00'",
  5874  			allegrosql:        "select time from %s where time = '2020-05-14 19:03:54.314615'",
  5875  			result:            []string{"2020-05-14 19:03:54.314615"},
  5876  		},
  5877  	}
  5878  	for _, cas := range cases {
  5879  		if len(cas.prepareALLEGROSQL) > 0 {
  5880  			tk.MustInterDirc(cas.prepareALLEGROSQL)
  5881  		}
  5882  		allegrosql := fmt.Sprintf(cas.allegrosql, "slow_query")
  5883  		tk.MustQuery(allegrosql).Check(solitonutil.RowsWithSep("|", cas.result...))
  5884  		allegrosql = fmt.Sprintf(cas.allegrosql, "cluster_slow_query")
  5885  		tk.MustQuery(allegrosql).Check(solitonutil.RowsWithSep("|", cas.result...))
  5886  	}
  5887  }
  5888  
  5889  func (s *testSuite1) TestIssue15718(c *C) {
  5890  	tk := testkit.NewTestKit(c, s.causetstore)
  5891  	tk.MustInterDirc("use test;")
  5892  	tk.MustInterDirc("drop causet if exists tt;")
  5893  	tk.MustInterDirc("create causet tt(a decimal(10, 0), b varchar(1), c time);")
  5894  	tk.MustInterDirc("insert into tt values(0, '2', null), (7, null, '1122'), (NULL, 'w', null), (NULL, '2', '3344'), (NULL, NULL, '0'), (7, 'f', '33');")
  5895  	tk.MustQuery("select a and b as d, a or c as e from tt;").Check(testkit.Rows("0 <nil>", "<nil> 1", "0 <nil>", "<nil> 1", "<nil> <nil>", "0 1"))
  5896  
  5897  	tk.MustInterDirc("drop causet if exists tt;")
  5898  	tk.MustInterDirc("create causet tt(a decimal(10, 0), b varchar(1), c time);")
  5899  	tk.MustInterDirc("insert into tt values(0, '2', '123'), (7, null, '1122'), (null, 'w', null);")
  5900  	tk.MustQuery("select a and b as d, a, b from tt order by d limit 1;").Check(testkit.Rows("<nil> 7 <nil>"))
  5901  	tk.MustQuery("select b or c as d, b, c from tt order by d limit 1;").Check(testkit.Rows("<nil> w <nil>"))
  5902  
  5903  	tk.MustInterDirc("drop causet if exists t0;")
  5904  	tk.MustInterDirc("CREATE TABLE t0(c0 FLOAT);")
  5905  	tk.MustInterDirc("INSERT INTO t0(c0) VALUES (NULL);")
  5906  	tk.MustQuery("SELECT * FROM t0 WHERE NOT(0 OR t0.c0);").Check(testkit.Rows())
  5907  }
  5908  
  5909  func (s *testSuite1) TestIssue15767(c *C) {
  5910  	tk := testkit.NewTestKit(c, s.causetstore)
  5911  	tk.MustInterDirc("use test;")
  5912  	tk.MustInterDirc("drop causet if exists tt;")
  5913  	tk.MustInterDirc("create causet t(a int, b char);")
  5914  	tk.MustInterDirc("insert into t values (1,'s'),(2,'b'),(1,'c'),(2,'e'),(1,'a');")
  5915  	tk.MustInterDirc("insert into t select * from t;")
  5916  	tk.MustInterDirc("insert into t select * from t;")
  5917  	tk.MustInterDirc("insert into t select * from t;")
  5918  	tk.MustQuery("select b, count(*) from ( select b from t order by a limit 20 offset 2) as s group by b order by b;").Check(testkit.Rows("a 6", "c 7", "s 7"))
  5919  }
  5920  
  5921  func (s *testSuite1) TestIssue16025(c *C) {
  5922  	tk := testkit.NewTestKit(c, s.causetstore)
  5923  	tk.MustInterDirc("use test;")
  5924  	tk.MustInterDirc("drop causet if exists t0;")
  5925  	tk.MustInterDirc("CREATE TABLE t0(c0 NUMERIC PRIMARY KEY);")
  5926  	tk.MustInterDirc("INSERT IGNORE INTO t0(c0) VALUES (NULL);")
  5927  	tk.MustQuery("SELECT * FROM t0 WHERE c0;").Check(testkit.Rows())
  5928  }
  5929  
  5930  func (s *testSuite1) TestIssue16854(c *C) {
  5931  	tk := testkit.NewTestKit(c, s.causetstore)
  5932  	tk.MustInterDirc("use test;")
  5933  	tk.MustInterDirc("drop causet if exists t;")
  5934  	tk.MustInterDirc("CREATE TABLE `t` (	`a` enum('WAITING','PRINTED','STOCKUP','CHECKED','OUTSTOCK','PICKEDUP','WILLBACK','BACKED') DEFAULT NULL)")
  5935  	tk.MustInterDirc("insert into t values(1),(2),(3),(4),(5),(6),(7);")
  5936  	for i := 0; i < 7; i++ {
  5937  		tk.MustInterDirc("insert into t select * from t;")
  5938  	}
  5939  	tk.MustInterDirc("set @@milevadb_max_chunk_size=100;")
  5940  	tk.MustQuery("select distinct a from t order by a").Check(testkit.Rows("WAITING", "PRINTED", "STOCKUP", "CHECKED", "OUTSTOCK", "PICKEDUP", "WILLBACK"))
  5941  	tk.MustInterDirc("drop causet t")
  5942  
  5943  	tk.MustInterDirc("CREATE TABLE `t` (	`a` set('WAITING','PRINTED','STOCKUP','CHECKED','OUTSTOCK','PICKEDUP','WILLBACK','BACKED') DEFAULT NULL)")
  5944  	tk.MustInterDirc("insert into t values(1),(2),(3),(4),(5),(6),(7);")
  5945  	for i := 0; i < 7; i++ {
  5946  		tk.MustInterDirc("insert into t select * from t;")
  5947  	}
  5948  	tk.MustInterDirc("set @@milevadb_max_chunk_size=100;")
  5949  	tk.MustQuery("select distinct a from t order by a").Check(testkit.Rows("WAITING", "PRINTED", "WAITING,PRINTED", "STOCKUP", "WAITING,STOCKUP", "PRINTED,STOCKUP", "WAITING,PRINTED,STOCKUP"))
  5950  	tk.MustInterDirc("drop causet t")
  5951  }
  5952  
  5953  func (s *testSuite) TestIssue16921(c *C) {
  5954  	tk := testkit.NewTestKitWithInit(c, s.causetstore)
  5955  
  5956  	tk.MustInterDirc("drop causet if exists t;")
  5957  	tk.MustInterDirc("create causet t (a float);")
  5958  	tk.MustInterDirc("create index a on t(a);")
  5959  	tk.MustInterDirc("insert into t values (1.0), (NULL), (0), (2.0);")
  5960  	tk.MustQuery("select `a` from `t` use index (a) where !`a`;").Check(testkit.Rows("0"))
  5961  	tk.MustQuery("select `a` from `t` ignore index (a) where !`a`;").Check(testkit.Rows("0"))
  5962  	tk.MustQuery("select `a` from `t` use index (a) where `a`;").Check(testkit.Rows("1", "2"))
  5963  	tk.MustQuery("select `a` from `t` ignore index (a) where `a`;").Check(testkit.Rows("1", "2"))
  5964  	tk.MustQuery("select a from t use index (a) where not a is true;").Check(testkit.Rows("<nil>", "0"))
  5965  	tk.MustQuery("select a from t use index (a) where not not a is true;").Check(testkit.Rows("1", "2"))
  5966  	tk.MustQuery("select a from t use index (a) where not not a;").Check(testkit.Rows("1", "2"))
  5967  	tk.MustQuery("select a from t use index (a) where not not not a is true;").Check(testkit.Rows("<nil>", "0"))
  5968  	tk.MustQuery("select a from t use index (a) where not not not a;").Check(testkit.Rows("0"))
  5969  }
  5970  
  5971  func (s *testSuite) TestIssue19100(c *C) {
  5972  	tk := testkit.NewTestKitWithInit(c, s.causetstore)
  5973  
  5974  	tk.MustInterDirc("drop causet if exists t1, t2;")
  5975  	tk.MustInterDirc("create causet t1 (c decimal);")
  5976  	tk.MustInterDirc("create causet t2 (c decimal, key(c));")
  5977  	tk.MustInterDirc("insert into t1 values (null);")
  5978  	tk.MustInterDirc("insert into t2 values (null);")
  5979  	tk.MustQuery("select count(*) from t1 where not c;").Check(testkit.Rows("0"))
  5980  	tk.MustQuery("select count(*) from t2 where not c;").Check(testkit.Rows("0"))
  5981  	tk.MustQuery("select count(*) from t1 where c;").Check(testkit.Rows("0"))
  5982  	tk.MustQuery("select count(*) from t2 where c;").Check(testkit.Rows("0"))
  5983  }
  5984  
  5985  // this is from jira issue #5856
  5986  func (s *testSuite1) TestInsertValuesWithSubQuery(c *C) {
  5987  	tk := testkit.NewTestKit(c, s.causetstore)
  5988  	tk.MustInterDirc("use test;")
  5989  	tk.MustInterDirc("drop causet if exists t2")
  5990  	tk.MustInterDirc("create causet t2(a int, b int, c int)")
  5991  	defer tk.MustInterDirc("drop causet if exists t2")
  5992  
  5993  	// should not reference upper scope
  5994  	c.Assert(tk.InterDircToErr("insert into t2 values (11, 8, (select not b))"), NotNil)
  5995  	c.Assert(tk.InterDircToErr("insert into t2 set a = 11, b = 8, c = (select b))"), NotNil)
  5996  
  5997  	// subquery reference target causet is allowed
  5998  	tk.MustInterDirc("insert into t2 values(1, 1, (select b from t2))")
  5999  	tk.MustQuery("select * from t2").Check(testkit.Rows("1 1 <nil>"))
  6000  	tk.MustInterDirc("insert into t2 set a = 1, b = 1, c = (select b+1 from t2)")
  6001  	tk.MustQuery("select * from t2").Check(testkit.Rows("1 1 <nil>", "1 1 2"))
  6002  
  6003  	// insert using defCausumn should work normally
  6004  	tk.MustInterDirc("delete from t2")
  6005  	tk.MustInterDirc("insert into t2 values(2, 4, a)")
  6006  	tk.MustQuery("select * from t2").Check(testkit.Rows("2 4 2"))
  6007  	tk.MustInterDirc("insert into t2 set a = 3, b = 5, c = b")
  6008  	tk.MustQuery("select * from t2").Check(testkit.Rows("2 4 2", "3 5 5"))
  6009  }
  6010  
  6011  func (s *testSuite1) TestDIVZeroInPartitionExpr(c *C) {
  6012  	tk := testkit.NewTestKit(c, s.causetstore)
  6013  	tk.MustInterDirc("use test;")
  6014  	tk.MustInterDirc("drop causet if exists t1")
  6015  	tk.MustInterDirc("create causet t1(a int) partition by range (10 div a) (partition p0 values less than (10), partition p1 values less than maxvalue)")
  6016  	defer tk.MustInterDirc("drop causet if exists t1")
  6017  
  6018  	tk.MustInterDirc("set @@sql_mode=''")
  6019  	tk.MustInterDirc("insert into t1 values (NULL), (0), (1)")
  6020  	tk.MustInterDirc("set @@sql_mode='STRICT_ALL_TABLES,ERROR_FOR_DIVISION_BY_ZERO'")
  6021  	tk.MustGetErrCode("insert into t1 values (NULL), (0), (1)", allegrosql.ErrDivisionByZero)
  6022  }
  6023  
  6024  func (s *testSuite1) TestInsertIntoGivenPartitionSet(c *C) {
  6025  	tk := testkit.NewTestKit(c, s.causetstore)
  6026  	tk.MustInterDirc("use test;")
  6027  	tk.MustInterDirc("drop causet if exists t1")
  6028  	tk.MustInterDirc(`create causet t1(
  6029  	a int(11) DEFAULT NULL,
  6030  	b varchar(10) DEFAULT NULL,
  6031  	UNIQUE KEY idx_a (a)) PARTITION BY RANGE (a)
  6032  	(PARTITION p0 VALUES LESS THAN (10) ENGINE = InnoDB,
  6033  	 PARTITION p1 VALUES LESS THAN (20) ENGINE = InnoDB,
  6034  	 PARTITION p2 VALUES LESS THAN (30) ENGINE = InnoDB,
  6035  	 PARTITION p3 VALUES LESS THAN (40) ENGINE = InnoDB,
  6036  	 PARTITION p4 VALUES LESS THAN MAXVALUE ENGINE = InnoDB)`)
  6037  	defer tk.MustInterDirc("drop causet if exists t1")
  6038  
  6039  	// insert into
  6040  	tk.MustInterDirc("insert into t1 partition(p0) values(1, 'a'), (2, 'b')")
  6041  	tk.MustQuery("select * from t1 partition(p0) order by a").Check(testkit.Rows("1 a", "2 b"))
  6042  	tk.MustInterDirc("insert into t1 partition(p0, p1) values(3, 'c'), (4, 'd')")
  6043  	tk.MustQuery("select * from t1 partition(p1)").Check(testkit.Rows())
  6044  
  6045  	err := tk.InterDircToErr("insert into t1 values(1, 'a')")
  6046  	c.Assert(err.Error(), Equals, "[ekv:1062]Duplicate entry '1' for key 'idx_a'")
  6047  
  6048  	err = tk.InterDircToErr("insert into t1 partition(p0, p_non_exist) values(1, 'a')")
  6049  	c.Assert(err.Error(), Equals, "[causet:1735]Unknown partition 'p_non_exist' in causet 't1'")
  6050  
  6051  	err = tk.InterDircToErr("insert into t1 partition(p0, p1) values(40, 'a')")
  6052  	c.Assert(err.Error(), Equals, "[causet:1748]Found a event not matching the given partition set")
  6053  
  6054  	// replace into
  6055  	tk.MustInterDirc("replace into t1 partition(p0) values(1, 'replace')")
  6056  	tk.MustInterDirc("replace into t1 partition(p0, p1) values(3, 'replace'), (4, 'replace')")
  6057  
  6058  	err = tk.InterDircToErr("replace into t1 values(1, 'a')")
  6059  	tk.MustQuery("select * from t1 partition (p0) order by a").Check(testkit.Rows("1 a", "2 b", "3 replace", "4 replace"))
  6060  
  6061  	err = tk.InterDircToErr("replace into t1 partition(p0, p_non_exist) values(1, 'a')")
  6062  	c.Assert(err.Error(), Equals, "[causet:1735]Unknown partition 'p_non_exist' in causet 't1'")
  6063  
  6064  	err = tk.InterDircToErr("replace into t1 partition(p0, p1) values(40, 'a')")
  6065  	c.Assert(err.Error(), Equals, "[causet:1748]Found a event not matching the given partition set")
  6066  
  6067  	tk.MustInterDirc("truncate causet t1")
  6068  
  6069  	tk.MustInterDirc("drop causet if exists t")
  6070  	tk.MustInterDirc("create causet t(a int, b char(10))")
  6071  	defer tk.MustInterDirc("drop causet if exists t")
  6072  
  6073  	// insert into general causet
  6074  	err = tk.InterDircToErr("insert into t partition(p0, p1) values(1, 'a')")
  6075  	c.Assert(err.Error(), Equals, "[causet:1747]PARTITION () clause on non partitioned causet")
  6076  
  6077  	// insert into from select
  6078  	tk.MustInterDirc("insert into t values(1, 'a'), (2, 'b')")
  6079  	tk.MustInterDirc("insert into t1 partition(p0) select * from t")
  6080  	tk.MustQuery("select * from t1 partition(p0) order by a").Check(testkit.Rows("1 a", "2 b"))
  6081  
  6082  	tk.MustInterDirc("truncate causet t")
  6083  	tk.MustInterDirc("insert into t values(3, 'c'), (4, 'd')")
  6084  	tk.MustInterDirc("insert into t1 partition(p0, p1) select * from t")
  6085  	tk.MustQuery("select * from t1 partition(p1) order by a").Check(testkit.Rows())
  6086  	tk.MustQuery("select * from t1 partition(p0) order by a").Check(testkit.Rows("1 a", "2 b", "3 c", "4 d"))
  6087  
  6088  	err = tk.InterDircToErr("insert into t1 select 1, 'a'")
  6089  	c.Assert(err.Error(), Equals, "[ekv:1062]Duplicate entry '1' for key 'idx_a'")
  6090  
  6091  	err = tk.InterDircToErr("insert into t1 partition(p0, p_non_exist) select 1, 'a'")
  6092  	c.Assert(err.Error(), Equals, "[causet:1735]Unknown partition 'p_non_exist' in causet 't1'")
  6093  
  6094  	err = tk.InterDircToErr("insert into t1 partition(p0, p1) select 40, 'a'")
  6095  	c.Assert(err.Error(), Equals, "[causet:1748]Found a event not matching the given partition set")
  6096  
  6097  	// replace into from select
  6098  	tk.MustInterDirc("replace into t1 partition(p0) select 1, 'replace'")
  6099  	tk.MustInterDirc("truncate causet t")
  6100  	tk.MustInterDirc("insert into t values(3, 'replace'), (4, 'replace')")
  6101  	tk.MustInterDirc("replace into t1 partition(p0, p1) select * from t")
  6102  
  6103  	err = tk.InterDircToErr("replace into t1 values select 1, 'a'")
  6104  	tk.MustQuery("select * from t1 partition (p0) order by a").Check(testkit.Rows("1 replace", "2 b", "3 replace", "4 replace"))
  6105  
  6106  	err = tk.InterDircToErr("replace into t1 partition(p0, p_non_exist) select 1, 'a'")
  6107  	c.Assert(err.Error(), Equals, "[causet:1735]Unknown partition 'p_non_exist' in causet 't1'")
  6108  
  6109  	err = tk.InterDircToErr("replace into t1 partition(p0, p1) select 40, 'a'")
  6110  	c.Assert(err.Error(), Equals, "[causet:1748]Found a event not matching the given partition set")
  6111  }
  6112  
  6113  func (s *testSuite1) TestUFIDelateGivenPartitionSet(c *C) {
  6114  	tk := testkit.NewTestKit(c, s.causetstore)
  6115  	tk.MustInterDirc("use test;")
  6116  	tk.MustInterDirc("drop causet if exists t1,t2,t3")
  6117  	tk.MustInterDirc(`create causet t1(
  6118  	a int(11),
  6119  	b varchar(10) DEFAULT NULL,
  6120  	primary key idx_a (a)) PARTITION BY RANGE (a)
  6121  	(PARTITION p0 VALUES LESS THAN (10) ENGINE = InnoDB,
  6122  	 PARTITION p1 VALUES LESS THAN (20) ENGINE = InnoDB,
  6123  	 PARTITION p2 VALUES LESS THAN (30) ENGINE = InnoDB,
  6124  	 PARTITION p3 VALUES LESS THAN (40) ENGINE = InnoDB,
  6125  	 PARTITION p4 VALUES LESS THAN MAXVALUE ENGINE = InnoDB)`)
  6126  
  6127  	tk.MustInterDirc(`create causet t2(
  6128  	a int(11) DEFAULT NULL,
  6129  	b varchar(10) DEFAULT NULL) PARTITION BY RANGE (a)
  6130  	(PARTITION p0 VALUES LESS THAN (10) ENGINE = InnoDB,
  6131  	 PARTITION p1 VALUES LESS THAN (20) ENGINE = InnoDB,
  6132  	 PARTITION p2 VALUES LESS THAN (30) ENGINE = InnoDB,
  6133  	 PARTITION p3 VALUES LESS THAN (40) ENGINE = InnoDB,
  6134  	 PARTITION p4 VALUES LESS THAN MAXVALUE ENGINE = InnoDB)`)
  6135  
  6136  	tk.MustInterDirc(`create causet t3 (a int(11), b varchar(10) default null)`)
  6137  
  6138  	defer tk.MustInterDirc("drop causet if exists t1,t2,t3")
  6139  	tk.MustInterDirc("insert into t3 values(1, 'a'), (2, 'b'), (11, 'c'), (21, 'd')")
  6140  	err := tk.InterDircToErr("uFIDelate t3 partition(p0) set a = 40 where a = 2")
  6141  	c.Assert(err.Error(), Equals, "[causet:1747]PARTITION () clause on non partitioned causet")
  6142  
  6143  	// uFIDelate with primary key change
  6144  	tk.MustInterDirc("insert into t1 values(1, 'a'), (2, 'b'), (11, 'c'), (21, 'd')")
  6145  	err = tk.InterDircToErr("uFIDelate t1 partition(p0, p1) set a = 40")
  6146  	c.Assert(err.Error(), Equals, "[causet:1748]Found a event not matching the given partition set")
  6147  	err = tk.InterDircToErr("uFIDelate t1 partition(p0) set a = 40 where a = 2")
  6148  	c.Assert(err.Error(), Equals, "[causet:1748]Found a event not matching the given partition set")
  6149  	// test non-exist partition.
  6150  	err = tk.InterDircToErr("uFIDelate t1 partition (p0, p_non_exist) set a = 40")
  6151  	c.Assert(err.Error(), Equals, "[causet:1735]Unknown partition 'p_non_exist' in causet 't1'")
  6152  	// test join.
  6153  	err = tk.InterDircToErr("uFIDelate t1 partition (p0), t3 set t1.a = 40 where t3.a = 2")
  6154  	c.Assert(err.Error(), Equals, "[causet:1748]Found a event not matching the given partition set")
  6155  
  6156  	tk.MustInterDirc("uFIDelate t1 partition(p0) set a = 3 where a = 2")
  6157  	tk.MustInterDirc("uFIDelate t1 partition(p0, p3) set a = 33 where a = 1")
  6158  
  6159  	// uFIDelate without partition change
  6160  	tk.MustInterDirc("insert into t2 values(1, 'a'), (2, 'b'), (11, 'c'), (21, 'd')")
  6161  	err = tk.InterDircToErr("uFIDelate t2 partition(p0, p1) set a = 40")
  6162  	c.Assert(err.Error(), Equals, "[causet:1748]Found a event not matching the given partition set")
  6163  	err = tk.InterDircToErr("uFIDelate t2 partition(p0) set a = 40 where a = 2")
  6164  	c.Assert(err.Error(), Equals, "[causet:1748]Found a event not matching the given partition set")
  6165  
  6166  	tk.MustInterDirc("uFIDelate t2 partition(p0) set a = 3 where a = 2")
  6167  	tk.MustInterDirc("uFIDelate t2 partition(p0, p3) set a = 33 where a = 1")
  6168  }
  6169  
  6170  func (s *testSuiteP2) TestApplyCache(c *C) {
  6171  	tk := testkit.NewTestKit(c, s.causetstore)
  6172  
  6173  	tk.MustInterDirc("use test;")
  6174  	tk.MustInterDirc("drop causet if exists t;")
  6175  	tk.MustInterDirc("create causet t(a int);")
  6176  	tk.MustInterDirc("insert into t values (1),(1),(1),(1),(1),(1),(1),(1),(1);")
  6177  	tk.MustInterDirc("analyze causet t;")
  6178  	result := tk.MustQuery("explain analyze SELECT count(1) FROM (SELECT (SELECT min(a) FROM t as t2 WHERE t2.a > t1.a) AS a from t as t1) t;")
  6179  	c.Assert(result.Rows()[1][0], Equals, "└─Apply_41")
  6180  	var (
  6181  		ind  int
  6182  		flag bool
  6183  	)
  6184  	value := (result.Rows()[1][5]).(string)
  6185  	for ind = 0; ind < len(value)-5; ind++ {
  6186  		if value[ind:ind+5] == "cache" {
  6187  			flag = true
  6188  			break
  6189  		}
  6190  	}
  6191  	c.Assert(flag, Equals, true)
  6192  	c.Assert(value[ind:], Equals, "cache:ON, cacheHitRatio:88.889%")
  6193  
  6194  	tk.MustInterDirc("drop causet if exists t;")
  6195  	tk.MustInterDirc("create causet t(a int);")
  6196  	tk.MustInterDirc("insert into t values (1),(2),(3),(4),(5),(6),(7),(8),(9);")
  6197  	tk.MustInterDirc("analyze causet t;")
  6198  	result = tk.MustQuery("explain analyze SELECT count(1) FROM (SELECT (SELECT min(a) FROM t as t2 WHERE t2.a > t1.a) AS a from t as t1) t;")
  6199  	c.Assert(result.Rows()[1][0], Equals, "└─Apply_41")
  6200  	flag = false
  6201  	value = (result.Rows()[1][5]).(string)
  6202  	for ind = 0; ind < len(value)-5; ind++ {
  6203  		if value[ind:ind+5] == "cache" {
  6204  			flag = true
  6205  			break
  6206  		}
  6207  	}
  6208  	c.Assert(flag, Equals, true)
  6209  	c.Assert(value[ind:], Equals, "cache:OFF")
  6210  }
  6211  
  6212  // For issue 17256
  6213  func (s *testSuite) TestGenerateDeferredCausetReplace(c *C) {
  6214  	tk := testkit.NewTestKit(c, s.causetstore)
  6215  	tk.MustInterDirc("use test;")
  6216  	tk.MustInterDirc("drop causet if exists t1")
  6217  	tk.MustInterDirc("create causet t1 (a int, b int as (a + 1) virtual not null, unique index idx(b));")
  6218  	tk.MustInterDirc("REPLACE INTO `t1` (`a`) VALUES (2);")
  6219  	tk.MustInterDirc("REPLACE INTO `t1` (`a`) VALUES (2);")
  6220  	tk.MustQuery("select * from t1").Check(testkit.Rows("2 3"))
  6221  	tk.MustInterDirc("insert into `t1` (`a`) VALUES (2) on duplicate key uFIDelate a = 3;")
  6222  	tk.MustQuery("select * from t1").Check(testkit.Rows("3 4"))
  6223  }
  6224  
  6225  func (s *testSlowQuery) TestSlowQueryWithoutSlowLog(c *C) {
  6226  	tk := testkit.NewTestKit(c, s.causetstore)
  6227  	originCfg := config.GetGlobalConfig()
  6228  	newCfg := *originCfg
  6229  	newCfg.Log.SlowQueryFile = "milevadb-slow-not-exist.log"
  6230  	newCfg.Log.SlowThreshold = math.MaxUint64
  6231  	config.StoreGlobalConfig(&newCfg)
  6232  	defer func() {
  6233  		config.StoreGlobalConfig(originCfg)
  6234  	}()
  6235  	tk.MustQuery("select query from information_schema.slow_query").Check(testkit.Rows())
  6236  	tk.MustQuery("select query from information_schema.slow_query where time > '2020-09-15 12:16:39' and time < now()").Check(testkit.Rows())
  6237  }
  6238  
  6239  func (s *testSlowQuery) TestSlowQuerySensitiveQuery(c *C) {
  6240  	tk := testkit.NewTestKit(c, s.causetstore)
  6241  	originCfg := config.GetGlobalConfig()
  6242  	newCfg := *originCfg
  6243  
  6244  	f, err := ioutil.TempFile("", "milevadb-slow-*.log")
  6245  	c.Assert(err, IsNil)
  6246  	f.Close()
  6247  	newCfg.Log.SlowQueryFile = f.Name()
  6248  	config.StoreGlobalConfig(&newCfg)
  6249  	defer func() {
  6250  		tk.MustInterDirc("set milevadb_slow_log_threshold=300;")
  6251  		config.StoreGlobalConfig(originCfg)
  6252  		os.Remove(newCfg.Log.SlowQueryFile)
  6253  	}()
  6254  	err = logutil.InitLogger(newCfg.Log.ToLogConfig())
  6255  	c.Assert(err, IsNil)
  6256  
  6257  	tk.MustInterDirc("set milevadb_slow_log_threshold=0;")
  6258  	tk.MustInterDirc("drop user if exists user_sensitive;")
  6259  	tk.MustInterDirc("create user user_sensitive identified by '123456789';")
  6260  	tk.MustInterDirc("alter user 'user_sensitive'@'%' identified by 'abcdefg';")
  6261  	tk.MustInterDirc("set password for 'user_sensitive'@'%' = 'xyzuvw';")
  6262  	tk.MustQuery("select query from `information_schema`.`slow_query` " +
  6263  		"where (query like 'set password%' or query like 'create user%' or query like 'alter user%') " +
  6264  		"and query like '%user_sensitive%' order by query;").
  6265  		Check(testkit.Rows(
  6266  			"alter user {user_sensitive@% password = ***};",
  6267  			"create user {user_sensitive@% password = ***};",
  6268  			"set password for user user_sensitive@%;",
  6269  		))
  6270  }
  6271  
  6272  func (s *testSerialSuite) TestKillBlockReader(c *C) {
  6273  	var retry = "github.com/whtcorpsinc/milevadb/causetstore/einsteindb/mockRetrySendReqToRegion"
  6274  	defer func() {
  6275  		c.Assert(failpoint.Disable(retry), IsNil)
  6276  	}()
  6277  	tk := testkit.NewTestKit(c, s.causetstore)
  6278  	tk.MustInterDirc("use test;")
  6279  	tk.MustInterDirc("drop causet if exists t")
  6280  	tk.MustInterDirc("create causet t (a int)")
  6281  	tk.MustInterDirc("insert into t values (1),(2),(3)")
  6282  	tk.MustInterDirc("set @@milevadb_allegrosql_scan_concurrency=1")
  6283  	atomic.StoreUint32(&tk.Se.GetStochastikVars().Killed, 0)
  6284  	c.Assert(failpoint.Enable(retry, `return(true)`), IsNil)
  6285  	wg := &sync.WaitGroup{}
  6286  	wg.Add(1)
  6287  	go func() {
  6288  		defer wg.Done()
  6289  		time.Sleep(1 * time.Second)
  6290  		err := tk.QueryToErr("select * from t")
  6291  		c.Assert(err, NotNil)
  6292  		c.Assert(int(terror.ToALLEGROSQLError(errors.Cause(err).(*terror.Error)).Code), Equals, int(interlock.ErrQueryInterrupted.Code()))
  6293  	}()
  6294  	atomic.StoreUint32(&tk.Se.GetStochastikVars().Killed, 1)
  6295  	wg.Wait()
  6296  }
  6297  
  6298  func (s *testSerialSuite) TestPrevStmtDesensitization(c *C) {
  6299  	tk := testkit.NewTestKit(c, s.causetstore)
  6300  	tk.MustInterDirc("use test;")
  6301  	oriCfg := config.GetGlobalConfig()
  6302  	defer config.StoreGlobalConfig(oriCfg)
  6303  	newCfg := *oriCfg
  6304  	newCfg.EnableRedactLog = 1
  6305  	config.StoreGlobalConfig(&newCfg)
  6306  	tk.MustInterDirc("drop causet if exists t")
  6307  	tk.MustInterDirc("create causet t (a int)")
  6308  	tk.MustInterDirc("begin")
  6309  	tk.MustInterDirc("insert into t values (1),(2)")
  6310  	c.Assert(tk.Se.GetStochastikVars().PrevStmt.String(), Equals, "insert into t values ( ? ) , ( ? )")
  6311  }
  6312  
  6313  func (s *testSuite) TestIssue19372(c *C) {
  6314  	tk := testkit.NewTestKit(c, s.causetstore)
  6315  	tk.MustInterDirc("use test;")
  6316  	tk.MustInterDirc("drop causet if exists t1, t2;")
  6317  	tk.MustInterDirc("create causet t1 (c_int int, c_str varchar(40), key(c_str));")
  6318  	tk.MustInterDirc("create causet t2 like t1;")
  6319  	tk.MustInterDirc("insert into t1 values (1, 'a'), (2, 'b'), (3, 'c');")
  6320  	tk.MustInterDirc("insert into t2 select * from t1;")
  6321  	tk.MustQuery("select (select t2.c_str from t2 where t2.c_str <= t1.c_str and t2.c_int in (1, 2) order by t2.c_str limit 1) x from t1 order by c_int;").Check(testkit.Rows("a", "a", "a"))
  6322  }
  6323  
  6324  func (s *testSerialSuite1) TestDefCauslectCopRuntimeStats(c *C) {
  6325  	tk := testkit.NewTestKit(c, s.causetstore)
  6326  	tk.MustInterDirc("use test;")
  6327  	tk.MustInterDirc("drop causet if exists t1")
  6328  	tk.MustInterDirc("create causet t1 (a int, b int)")
  6329  	tk.MustInterDirc("set milevadb_enable_defCauslect_execution_info=1;")
  6330  	c.Assert(failpoint.Enable("github.com/whtcorpsinc/milevadb/causetstore/einsteindb/einsteindbStoreRespResult", `return(true)`), IsNil)
  6331  	rows := tk.MustQuery("explain analyze select * from t1").Rows()
  6332  	c.Assert(len(rows), Equals, 2)
  6333  	explain := fmt.Sprintf("%v", rows[0])
  6334  	c.Assert(explain, Matches, ".*rpc_num: 2, .*regionMiss:.*")
  6335  	c.Assert(failpoint.Disable("github.com/whtcorpsinc/milevadb/causetstore/einsteindb/einsteindbStoreRespResult"), IsNil)
  6336  }
  6337  
  6338  func (s *testSuite) TestDefCauslectDMLRuntimeStats(c *C) {
  6339  	tk := testkit.NewTestKit(c, s.causetstore)
  6340  	tk.MustInterDirc("use test")
  6341  	tk.MustInterDirc("drop causet if exists t1")
  6342  	tk.MustInterDirc("create causet t1 (a int, b int, unique index (a))")
  6343  
  6344  	testALLEGROSQLs := []string{
  6345  		"insert ignore into t1 values (5,5);",
  6346  		"insert into t1 values (5,5) on duplicate key uFIDelate a=a+1;",
  6347  		"replace into t1 values (5,6),(6,7)",
  6348  		"uFIDelate t1 set a=a+1 where a=6;",
  6349  	}
  6350  
  6351  	getRootStats := func() string {
  6352  		info := tk.Se.ShowProcess()
  6353  		c.Assert(info, NotNil)
  6354  		p, ok := info.Causet.(causetembedded.Causet)
  6355  		c.Assert(ok, IsTrue)
  6356  		stats := tk.Se.GetStochastikVars().StmtCtx.RuntimeStatsDefCausl.GetRootStats(p.ID())
  6357  		return stats.String()
  6358  	}
  6359  	for _, allegrosql := range testALLEGROSQLs {
  6360  		tk.MustInterDirc(allegrosql)
  6361  		c.Assert(getRootStats(), Matches, "time.*loops.*Get.*num_rpc.*total_time.*")
  6362  	}
  6363  
  6364  	// Test for dagger keys stats.
  6365  	tk.MustInterDirc("begin pessimistic")
  6366  	tk.MustInterDirc("uFIDelate t1 set b=b+1")
  6367  	c.Assert(getRootStats(), Matches, "time.*lock_keys.*time.* region.* keys.* lock_rpc:.* rpc_count.*")
  6368  	tk.MustInterDirc("rollback")
  6369  
  6370  	tk.MustInterDirc("begin pessimistic")
  6371  	tk.MustQuery("select * from t1 for uFIDelate").Check(testkit.Rows("5 6", "7 7"))
  6372  	c.Assert(getRootStats(), Matches, "time.*lock_keys.*time.* region.* keys.* lock_rpc:.* rpc_count.*")
  6373  	tk.MustInterDirc("rollback")
  6374  
  6375  	tk.MustInterDirc("begin pessimistic")
  6376  	tk.MustInterDirc("insert ignore into t1 values (9,9)")
  6377  	c.Assert(getRootStats(), Matches, "time:.*, loops:.*, BatchGet:{num_rpc:.*, total_time:.*}, lock_keys: {time:.*, region:.*, keys:.*, lock_rpc:.*, rpc_count:.*}")
  6378  	tk.MustInterDirc("rollback")
  6379  }
  6380  
  6381  func (s *testSuite) TestIssue13758(c *C) {
  6382  	tk := testkit.NewTestKit(c, s.causetstore)
  6383  	tk.MustInterDirc("use test")
  6384  	tk.MustInterDirc("drop causet if exists t1, t2")
  6385  	tk.MustInterDirc("create causet t1 (pk int(11) primary key, a int(11) not null, b int(11), key idx_b(b), key idx_a(a))")
  6386  	tk.MustInterDirc("insert into `t1` values (1,1,0),(2,7,6),(3,2,null),(4,1,null),(5,4,5)")
  6387  	tk.MustInterDirc("create causet t2 (a int)")
  6388  	tk.MustInterDirc("insert into t2 values (1),(null)")
  6389  	tk.MustQuery("select (select a from t1 use index(idx_a) where b >= t2.a order by a limit 1) as field from t2").Check(testkit.Rows(
  6390  		"4",
  6391  		"<nil>",
  6392  	))
  6393  }