github.com/whtcorpsinc/milevadb-prod@v0.0.0-20211104133533-f57f4be3b597/interlock/seqtest/seq_executor_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  // Note: All the tests in this file will be executed sequentially.
    15  
    16  package interlock_test
    17  
    18  import (
    19  	"bytes"
    20  	"context"
    21  	"flag"
    22  	"fmt"
    23  	"math"
    24  	"os"
    25  	"runtime/pprof"
    26  	"strconv"
    27  	"strings"
    28  	"sync"
    29  	"sync/atomic"
    30  	"testing"
    31  	"time"
    32  
    33  	"github.com/whtcorpsinc/BerolinaSQL"
    34  	"github.com/whtcorpsinc/BerolinaSQL/allegrosql"
    35  	"github.com/whtcorpsinc/BerolinaSQL/perceptron"
    36  	"github.com/whtcorpsinc/BerolinaSQL/terror"
    37  	. "github.com/whtcorpsinc/check"
    38  	pb "github.com/whtcorpsinc/ekvproto/pkg/ekvrpcpb"
    39  	"github.com/whtcorpsinc/errors"
    40  	"github.com/whtcorpsinc/failpoint"
    41  	causetembedded "github.com/whtcorpsinc/milevadb/causet/embedded"
    42  	"github.com/whtcorpsinc/milevadb/causetstore/einsteindb"
    43  	"github.com/whtcorpsinc/milevadb/causetstore/einsteindb/einsteindbrpc"
    44  	"github.com/whtcorpsinc/milevadb/causetstore/mockstore"
    45  	"github.com/whtcorpsinc/milevadb/causetstore/mockstore/cluster"
    46  	"github.com/whtcorpsinc/milevadb/config"
    47  	"github.com/whtcorpsinc/milevadb/dbs"
    48  	dbssolitonutil "github.com/whtcorpsinc/milevadb/dbs/solitonutil"
    49  	"github.com/whtcorpsinc/milevadb/ekv"
    50  	"github.com/whtcorpsinc/milevadb/errno"
    51  	"github.com/whtcorpsinc/milevadb/interlock"
    52  	"github.com/whtcorpsinc/milevadb/petri"
    53  	"github.com/whtcorpsinc/milevadb/soliton/defCauslate"
    54  	"github.com/whtcorpsinc/milevadb/soliton/gcutil"
    55  	"github.com/whtcorpsinc/milevadb/soliton/logutil"
    56  	"github.com/whtcorpsinc/milevadb/soliton/mock"
    57  	"github.com/whtcorpsinc/milevadb/soliton/solitonutil"
    58  	"github.com/whtcorpsinc/milevadb/soliton/testkit"
    59  	"github.com/whtcorpsinc/milevadb/spacetime/autoid"
    60  	"github.com/whtcorpsinc/milevadb/statistics/handle"
    61  	"github.com/whtcorpsinc/milevadb/stochastik"
    62  	"github.com/whtcorpsinc/milevadb/stochastikctx/variable"
    63  )
    64  
    65  func TestT(t *testing.T) {
    66  	CustomVerboseFlag = true
    67  	logLevel := os.Getenv("log_level")
    68  	logutil.InitLogger(logutil.NewLogConfig(logLevel, logutil.DefaultLogFormat, "", logutil.EmptyFileLogConfig, false))
    69  	TestingT(t)
    70  }
    71  
    72  var _ = SerialSuites(&seqTestSuite{})
    73  var _ = SerialSuites(&seqTestSuite1{})
    74  
    75  type seqTestSuite struct {
    76  	cluster     cluster.Cluster
    77  	causetstore ekv.CausetStorage
    78  	petri       *petri.Petri
    79  	*BerolinaSQL.BerolinaSQL
    80  	ctx *mock.Context
    81  }
    82  
    83  var mockEinsteinDB = flag.Bool("mockEinsteinDB", true, "use mock einsteindb causetstore in interlock test")
    84  
    85  func (s *seqTestSuite) SetUpSuite(c *C) {
    86  	s.BerolinaSQL = BerolinaSQL.New()
    87  	flag.Lookup("mockEinsteinDB")
    88  	useMockEinsteinDB := *mockEinsteinDB
    89  	if useMockEinsteinDB {
    90  		var err error
    91  		s.causetstore, err = mockstore.NewMockStore(
    92  			mockstore.WithClusterInspector(func(c cluster.Cluster) {
    93  				mockstore.BootstrapWithSingleStore(c)
    94  				s.cluster = c
    95  			}),
    96  		)
    97  		c.Assert(err, IsNil)
    98  		stochastik.SetSchemaLease(0)
    99  		stochastik.DisableStats4Test()
   100  	}
   101  	d, err := stochastik.BootstrapStochastik(s.causetstore)
   102  	c.Assert(err, IsNil)
   103  	d.SetStatsUFIDelating(true)
   104  	s.petri = d
   105  }
   106  
   107  func (s *seqTestSuite) TearDownSuite(c *C) {
   108  	s.petri.Close()
   109  	s.causetstore.Close()
   110  }
   111  
   112  func (s *seqTestSuite) TestEarlyClose(c *C) {
   113  	tk := testkit.NewTestKit(c, s.causetstore)
   114  	tk.MustInterDirc("use test")
   115  	tk.MustInterDirc("create causet earlyclose (id int primary key)")
   116  
   117  	N := 100
   118  	// Insert N rows.
   119  	var values []string
   120  	for i := 0; i < N; i++ {
   121  		values = append(values, fmt.Sprintf("(%d)", i))
   122  	}
   123  	tk.MustInterDirc("insert earlyclose values " + strings.Join(values, ","))
   124  
   125  	// Get causet ID for split.
   126  	dom := petri.GetPetri(tk.Se)
   127  	is := dom.SchemaReplicant()
   128  	tbl, err := is.BlockByName(perceptron.NewCIStr("test"), perceptron.NewCIStr("earlyclose"))
   129  	c.Assert(err, IsNil)
   130  	tblID := tbl.Meta().ID
   131  
   132  	// Split the causet.
   133  	s.cluster.SplitBlock(tblID, N/2)
   134  
   135  	ctx := context.Background()
   136  	for i := 0; i < N/2; i++ {
   137  		rss, err1 := tk.Se.InterDircute(ctx, "select * from earlyclose order by id")
   138  		c.Assert(err1, IsNil)
   139  		rs := rss[0]
   140  		req := rs.NewChunk()
   141  		err = rs.Next(ctx, req)
   142  		c.Assert(err, IsNil)
   143  		rs.Close()
   144  	}
   145  
   146  	// Goroutine should not leak when error happen.
   147  	c.Assert(failpoint.Enable("github.com/whtcorpsinc/milevadb/causetstore/einsteindb/handleTaskOnceError", `return(true)`), IsNil)
   148  	defer func() {
   149  		c.Assert(failpoint.Disable("github.com/whtcorpsinc/milevadb/causetstore/einsteindb/handleTaskOnceError"), IsNil)
   150  	}()
   151  	rss, err := tk.Se.InterDircute(ctx, "select * from earlyclose")
   152  	c.Assert(err, IsNil)
   153  	rs := rss[0]
   154  	req := rs.NewChunk()
   155  	err = rs.Next(ctx, req)
   156  	c.Assert(err, NotNil)
   157  	rs.Close()
   158  }
   159  
   160  type stats struct {
   161  }
   162  
   163  func (s stats) GetScope(status string) variable.ScopeFlag { return variable.DefaultStatusVarScopeFlag }
   164  
   165  func (s stats) Stats(vars *variable.StochastikVars) (map[string]interface{}, error) {
   166  	m := make(map[string]interface{})
   167  	var a, b interface{}
   168  	b = "123"
   169  	m["test_interface_nil"] = a
   170  	m["test_interface"] = b
   171  	m["test_interface_slice"] = []interface{}{"a", "b", "c"}
   172  	return m, nil
   173  }
   174  
   175  func (s *seqTestSuite) TestShow(c *C) {
   176  	tk := testkit.NewTestKit(c, s.causetstore)
   177  	tk.MustInterDirc("use test")
   178  
   179  	testALLEGROSQL := `drop causet if exists show_test`
   180  	tk.MustInterDirc(testALLEGROSQL)
   181  	testALLEGROSQL = `create causet SHOW_test (id int PRIMARY KEY AUTO_INCREMENT, c1 int comment "c1_comment", c2 int, c3 int default 1, c4 text, c5 boolean, key idx_wide_c4(c3, c4(10))) ENGINE=InnoDB AUTO_INCREMENT=28934 DEFAULT CHARSET=utf8 COMMENT "block_comment";`
   182  	tk.MustInterDirc(testALLEGROSQL)
   183  
   184  	testALLEGROSQL = "show defCausumns from show_test;"
   185  	result := tk.MustQuery(testALLEGROSQL)
   186  	c.Check(result.Events(), HasLen, 6)
   187  
   188  	testALLEGROSQL = "show create causet show_test;"
   189  	result = tk.MustQuery(testALLEGROSQL)
   190  	c.Check(result.Events(), HasLen, 1)
   191  	event := result.Events()[0]
   192  	// For issue https://github.com/whtcorpsinc/milevadb/issues/1061
   193  	expectedEvent := []interface{}{
   194  		"SHOW_test", "CREATE TABLE `SHOW_test` (\n  `id` int(11) NOT NULL AUTO_INCREMENT,\n  `c1` int(11) DEFAULT NULL COMMENT 'c1_comment',\n  `c2` int(11) DEFAULT NULL,\n  `c3` int(11) DEFAULT 1,\n  `c4` text DEFAULT NULL,\n  `c5` tinyint(1) DEFAULT NULL,\n  PRIMARY KEY (`id`),\n  KEY `idx_wide_c4` (`c3`,`c4`(10))\n) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin AUTO_INCREMENT=28934 COMMENT='block_comment'"}
   195  	for i, r := range event {
   196  		c.Check(r, Equals, expectedEvent[i])
   197  	}
   198  
   199  	// For issue https://github.com/whtcorpsinc/milevadb/issues/1918
   200  	testALLEGROSQL = `create causet ptest(
   201  		a int primary key,
   202  		b double NOT NULL DEFAULT 2.0,
   203  		c varchar(10) NOT NULL,
   204  		d time unique,
   205  		e timestamp NULL,
   206  		f timestamp
   207  	);`
   208  	tk.MustInterDirc(testALLEGROSQL)
   209  	testALLEGROSQL = "show create causet ptest;"
   210  	result = tk.MustQuery(testALLEGROSQL)
   211  	c.Check(result.Events(), HasLen, 1)
   212  	event = result.Events()[0]
   213  	expectedEvent = []interface{}{
   214  		"ptest", "CREATE TABLE `ptest` (\n  `a` int(11) NOT NULL,\n  `b` double NOT NULL DEFAULT 2.0,\n  `c` varchar(10) NOT NULL,\n  `d` time DEFAULT NULL,\n  `e` timestamp NULL DEFAULT NULL,\n  `f` timestamp NULL DEFAULT NULL,\n  PRIMARY KEY (`a`),\n  UNIQUE KEY `d` (`d`)\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin"}
   215  	for i, r := range event {
   216  		c.Check(r, Equals, expectedEvent[i])
   217  	}
   218  
   219  	// Issue #4684.
   220  	tk.MustInterDirc("drop causet if exists `t1`")
   221  	testALLEGROSQL = "create causet `t1` (" +
   222  		"`c1` tinyint unsigned default null," +
   223  		"`c2` smallint unsigned default null," +
   224  		"`c3` mediumint unsigned default null," +
   225  		"`c4` int unsigned default null," +
   226  		"`c5` bigint unsigned default null);"
   227  
   228  	tk.MustInterDirc(testALLEGROSQL)
   229  	testALLEGROSQL = "show create causet t1"
   230  	result = tk.MustQuery(testALLEGROSQL)
   231  	c.Check(result.Events(), HasLen, 1)
   232  	event = result.Events()[0]
   233  	expectedEvent = []interface{}{
   234  		"t1", "CREATE TABLE `t1` (\n" +
   235  			"  `c1` tinyint(3) unsigned DEFAULT NULL,\n" +
   236  			"  `c2` smallint(5) unsigned DEFAULT NULL,\n" +
   237  			"  `c3` mediumint(8) unsigned DEFAULT NULL,\n" +
   238  			"  `c4` int(10) unsigned DEFAULT NULL,\n" +
   239  			"  `c5` bigint(20) unsigned DEFAULT NULL\n" +
   240  			") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin"}
   241  	for i, r := range event {
   242  		c.Check(r, Equals, expectedEvent[i])
   243  	}
   244  
   245  	// Issue #7665
   246  	tk.MustInterDirc("drop causet if exists `decimalschema`")
   247  	testALLEGROSQL = "create causet `decimalschema` (`c1` decimal);"
   248  	tk.MustInterDirc(testALLEGROSQL)
   249  	testALLEGROSQL = "show create causet decimalschema"
   250  	result = tk.MustQuery(testALLEGROSQL)
   251  	c.Check(result.Events(), HasLen, 1)
   252  	event = result.Events()[0]
   253  	expectedEvent = []interface{}{
   254  		"decimalschema", "CREATE TABLE `decimalschema` (\n" +
   255  			"  `c1` decimal(11,0) DEFAULT NULL\n" +
   256  			") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin"}
   257  	for i, r := range event {
   258  		c.Check(r, Equals, expectedEvent[i])
   259  	}
   260  
   261  	tk.MustInterDirc("drop causet if exists `decimalschema`")
   262  	testALLEGROSQL = "create causet `decimalschema` (`c1` decimal(15));"
   263  	tk.MustInterDirc(testALLEGROSQL)
   264  	testALLEGROSQL = "show create causet decimalschema"
   265  	result = tk.MustQuery(testALLEGROSQL)
   266  	c.Check(result.Events(), HasLen, 1)
   267  	event = result.Events()[0]
   268  	expectedEvent = []interface{}{
   269  		"decimalschema", "CREATE TABLE `decimalschema` (\n" +
   270  			"  `c1` decimal(15,0) DEFAULT NULL\n" +
   271  			") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin"}
   272  	for i, r := range event {
   273  		c.Check(r, Equals, expectedEvent[i])
   274  	}
   275  
   276  	// test SHOW CREATE TABLE with invisible index
   277  	tk.MustInterDirc("drop causet if exists t")
   278  	tk.MustInterDirc(`create causet t (
   279  		a int,
   280  		b int,
   281  		c int UNIQUE KEY,
   282  		d int UNIQUE KEY,
   283  		index invisible_idx_b (b) invisible,
   284  		index (d) invisible)`)
   285  	expected :=
   286  		"t CREATE TABLE `t` (\n" +
   287  			"  `a` int(11) DEFAULT NULL,\n" +
   288  			"  `b` int(11) DEFAULT NULL,\n" +
   289  			"  `c` int(11) DEFAULT NULL,\n" +
   290  			"  `d` int(11) DEFAULT NULL,\n" +
   291  			"  KEY `invisible_idx_b` (`b`) /*!80000 INVISIBLE */,\n" +
   292  			"  KEY `d` (`d`) /*!80000 INVISIBLE */,\n" +
   293  			"  UNIQUE KEY `c` (`c`),\n" +
   294  			"  UNIQUE KEY `d_2` (`d`)\n" +
   295  			") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin"
   296  	tk.MustQuery("show create causet t").Check(testkit.Events(expected))
   297  	tk.MustInterDirc("drop causet t")
   298  
   299  	testALLEGROSQL = "SHOW VARIABLES LIKE 'character_set_results';"
   300  	result = tk.MustQuery(testALLEGROSQL)
   301  	c.Check(result.Events(), HasLen, 1)
   302  
   303  	// Test case for index type and comment
   304  	tk.MustInterDirc(`create causet show_index (id int, c int, primary key (id), index cIdx using hash (c) comment "index_comment_for_cIdx");`)
   305  	tk.MustInterDirc(`create index idx1 on show_index (id) using hash;`)
   306  	tk.MustInterDirc(`create index idx2 on show_index (id) comment 'idx';`)
   307  	tk.MustInterDirc(`create index idx3 on show_index (id) using hash comment 'idx';`)
   308  	tk.MustInterDirc(`alter causet show_index add index idx4 (id) using btree comment 'idx';`)
   309  	tk.MustInterDirc(`create index idx5 using hash on show_index (id) using btree comment 'idx';`)
   310  	tk.MustInterDirc(`create index idx6 using hash on show_index (id);`)
   311  	tk.MustInterDirc(`create index idx7 on show_index (id);`)
   312  	tk.MustInterDirc(`create index idx8 on show_index (id) visible;`)
   313  	tk.MustInterDirc(`create index idx9 on show_index (id) invisible;`)
   314  	tk.MustInterDirc(`create index expr_idx on show_index ((id*2+1))`)
   315  	testALLEGROSQL = "SHOW index from show_index;"
   316  	tk.MustQuery(testALLEGROSQL).Check(solitonutil.EventsWithSep("|",
   317  		"show_index|0|PRIMARY|1|id|A|0|<nil>|<nil>||BTREE| |YES|NULL",
   318  		"show_index|1|cIdx|1|c|A|0|<nil>|<nil>|YES|HASH||index_comment_for_cIdx|YES|NULL",
   319  		"show_index|1|idx1|1|id|A|0|<nil>|<nil>|YES|HASH| |YES|NULL",
   320  		"show_index|1|idx2|1|id|A|0|<nil>|<nil>|YES|BTREE||idx|YES|NULL",
   321  		"show_index|1|idx3|1|id|A|0|<nil>|<nil>|YES|HASH||idx|YES|NULL",
   322  		"show_index|1|idx4|1|id|A|0|<nil>|<nil>|YES|BTREE||idx|YES|NULL",
   323  		"show_index|1|idx5|1|id|A|0|<nil>|<nil>|YES|BTREE||idx|YES|NULL",
   324  		"show_index|1|idx6|1|id|A|0|<nil>|<nil>|YES|HASH| |YES|NULL",
   325  		"show_index|1|idx7|1|id|A|0|<nil>|<nil>|YES|BTREE| |YES|NULL",
   326  		"show_index|1|idx8|1|id|A|0|<nil>|<nil>|YES|BTREE| |YES|NULL",
   327  		"show_index|1|idx9|1|id|A|0|<nil>|<nil>|YES|BTREE| |NO|NULL",
   328  		"show_index|1|expr_idx|1|NULL|A|0|<nil>|<nil>|YES|BTREE| |YES|(`id` * 2 + 1)",
   329  	))
   330  
   331  	// For show like with escape
   332  	testALLEGROSQL = `show blocks like 'SHOW\_test'`
   333  	result = tk.MustQuery(testALLEGROSQL)
   334  	rows := result.Events()
   335  	c.Check(rows, HasLen, 1)
   336  	c.Check(rows[0], DeepEquals, []interface{}{"SHOW_test"})
   337  
   338  	var ss stats
   339  	variable.RegisterStatistics(ss)
   340  	testALLEGROSQL = "show status like 'character_set_results';"
   341  	result = tk.MustQuery(testALLEGROSQL)
   342  	c.Check(result.Events(), NotNil)
   343  
   344  	tk.MustQuery("SHOW PROCEDURE STATUS WHERE EDB='test'").Check(testkit.Events())
   345  	tk.MustQuery("SHOW TRIGGERS WHERE `Trigger` ='test'").Check(testkit.Events())
   346  	tk.MustQuery("SHOW PROCESSLIST;").Check(testkit.Events())
   347  	tk.MustQuery("SHOW FULL PROCESSLIST;").Check(testkit.Events())
   348  	tk.MustQuery("SHOW EVENTS WHERE EDB = 'test'").Check(testkit.Events())
   349  	tk.MustQuery("SHOW PLUGINS").Check(testkit.Events())
   350  	tk.MustQuery("SHOW PROFILES").Check(testkit.Events())
   351  
   352  	// +-------------+--------------------+--------------+------------------+-------------------+
   353  	// | File        | Position           | Binlog_Do_DB | Binlog_Ignore_DB | InterDircuted_Gtid_Set |
   354  	// +-------------+--------------------+--------------+------------------+-------------------+
   355  	// | milevadb-binlog | 400668057259474944 |              |                  |                   |
   356  	// +-------------+--------------------+--------------+------------------+-------------------+
   357  	result = tk.MustQuery("SHOW MASTER STATUS")
   358  	c.Check(result.Events(), HasLen, 1)
   359  	event = result.Events()[0]
   360  	c.Check(event, HasLen, 5)
   361  	c.Assert(event[1].(string) != "0", IsTrue)
   362  
   363  	tk.MustQuery("SHOW PRIVILEGES")
   364  
   365  	// Test show create database
   366  	testALLEGROSQL = `create database show_test_DB`
   367  	tk.MustInterDirc(testALLEGROSQL)
   368  	testALLEGROSQL = "show create database show_test_DB;"
   369  	tk.MustQuery(testALLEGROSQL).Check(solitonutil.EventsWithSep("|",
   370  		"show_test_DB|CREATE DATABASE `show_test_DB` /*!40100 DEFAULT CHARACTER SET utf8mb4 */",
   371  	))
   372  	testALLEGROSQL = "show create database if not exists show_test_DB;"
   373  	tk.MustQuery(testALLEGROSQL).Check(solitonutil.EventsWithSep("|",
   374  		"show_test_DB|CREATE DATABASE /*!32312 IF NOT EXISTS*/ `show_test_DB` /*!40100 DEFAULT CHARACTER SET utf8mb4 */",
   375  	))
   376  
   377  	tk.MustInterDirc("use show_test_DB")
   378  	result = tk.MustQuery("SHOW index from show_index from test where DeferredCauset_name = 'c'")
   379  	c.Check(result.Events(), HasLen, 1)
   380  
   381  	// Test show full defCausumns
   382  	// for issue https://github.com/whtcorpsinc/milevadb/issues/4224
   383  	tk.MustInterDirc(`drop causet if exists show_test_comment`)
   384  	tk.MustInterDirc(`create causet show_test_comment (id int not null default 0 comment "show_test_comment_id")`)
   385  	tk.MustQuery(`show full defCausumns from show_test_comment`).Check(solitonutil.EventsWithSep("|",
   386  		"id|int(11)|<nil>|NO||0||select,insert,uFIDelate,references|show_test_comment_id",
   387  	))
   388  
   389  	// Test show create causet with AUTO_INCREMENT option
   390  	// for issue https://github.com/whtcorpsinc/milevadb/issues/3747
   391  	tk.MustInterDirc(`drop causet if exists show_auto_increment`)
   392  	tk.MustInterDirc(`create causet show_auto_increment (id int key auto_increment) auto_increment=4`)
   393  	tk.MustQuery(`show create causet show_auto_increment`).Check(solitonutil.EventsWithSep("|",
   394  		""+
   395  			"show_auto_increment CREATE TABLE `show_auto_increment` (\n"+
   396  			"  `id` int(11) NOT NULL AUTO_INCREMENT,\n"+
   397  			"  PRIMARY KEY (`id`)\n"+
   398  			") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin AUTO_INCREMENT=4",
   399  	))
   400  	// for issue https://github.com/whtcorpsinc/milevadb/issues/4678
   401  	autoIDStep := autoid.GetStep()
   402  	tk.MustInterDirc("insert into show_auto_increment values(20)")
   403  	autoID := autoIDStep + 21
   404  	tk.MustQuery(`show create causet show_auto_increment`).Check(solitonutil.EventsWithSep("|",
   405  		""+
   406  			"show_auto_increment CREATE TABLE `show_auto_increment` (\n"+
   407  			"  `id` int(11) NOT NULL AUTO_INCREMENT,\n"+
   408  			"  PRIMARY KEY (`id`)\n"+
   409  			") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin AUTO_INCREMENT="+strconv.Itoa(int(autoID)),
   410  	))
   411  	tk.MustInterDirc(`drop causet show_auto_increment`)
   412  	tk.MustInterDirc(`create causet show_auto_increment (id int primary key auto_increment)`)
   413  	tk.MustQuery(`show create causet show_auto_increment`).Check(solitonutil.EventsWithSep("|",
   414  		""+
   415  			"show_auto_increment CREATE TABLE `show_auto_increment` (\n"+
   416  			"  `id` int(11) NOT NULL AUTO_INCREMENT,\n"+
   417  			"  PRIMARY KEY (`id`)\n"+
   418  			") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin",
   419  	))
   420  	tk.MustInterDirc("insert into show_auto_increment values(10)")
   421  	autoID = autoIDStep + 11
   422  	tk.MustQuery(`show create causet show_auto_increment`).Check(solitonutil.EventsWithSep("|",
   423  		""+
   424  			"show_auto_increment CREATE TABLE `show_auto_increment` (\n"+
   425  			"  `id` int(11) NOT NULL AUTO_INCREMENT,\n"+
   426  			"  PRIMARY KEY (`id`)\n"+
   427  			") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin AUTO_INCREMENT="+strconv.Itoa(int(autoID)),
   428  	))
   429  
   430  	// Test show causet with defCausumn's comment contain escape character
   431  	// for issue https://github.com/whtcorpsinc/milevadb/issues/4411
   432  	tk.MustInterDirc(`drop causet if exists show_escape_character`)
   433  	tk.MustInterDirc(`create causet show_escape_character(id int comment 'a\rb\nc\td\0ef')`)
   434  	tk.MustQuery(`show create causet show_escape_character`).Check(solitonutil.EventsWithSep("|",
   435  		""+
   436  			"show_escape_character CREATE TABLE `show_escape_character` (\n"+
   437  			"  `id` int(11) DEFAULT NULL COMMENT 'a\\rb\\nc	d\\0ef'\n"+
   438  			") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin",
   439  	))
   440  
   441  	// for issue https://github.com/whtcorpsinc/milevadb/issues/4424
   442  	tk.MustInterDirc("drop causet if exists show_test")
   443  	testALLEGROSQL = `create causet show_test(
   444  		a varchar(10) COMMENT 'a\nb\rc\td\0e'
   445  	) COMMENT='a\nb\rc\td\0e';`
   446  	tk.MustInterDirc(testALLEGROSQL)
   447  	testALLEGROSQL = "show create causet show_test;"
   448  	result = tk.MustQuery(testALLEGROSQL)
   449  	c.Check(result.Events(), HasLen, 1)
   450  	event = result.Events()[0]
   451  	expectedEvent = []interface{}{
   452  		"show_test", "CREATE TABLE `show_test` (\n  `a` varchar(10) DEFAULT NULL COMMENT 'a\\nb\\rc	d\\0e'\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT='a\\nb\\rc	d\\0e'"}
   453  	for i, r := range event {
   454  		c.Check(r, Equals, expectedEvent[i])
   455  	}
   456  
   457  	// for issue https://github.com/whtcorpsinc/milevadb/issues/4425
   458  	tk.MustInterDirc("drop causet if exists show_test")
   459  	testALLEGROSQL = `create causet show_test(
   460  		a varchar(10) DEFAULT 'a\nb\rc\td\0e'
   461  	);`
   462  	tk.MustInterDirc(testALLEGROSQL)
   463  	testALLEGROSQL = "show create causet show_test;"
   464  	result = tk.MustQuery(testALLEGROSQL)
   465  	c.Check(result.Events(), HasLen, 1)
   466  	event = result.Events()[0]
   467  	expectedEvent = []interface{}{
   468  		"show_test", "CREATE TABLE `show_test` (\n  `a` varchar(10) DEFAULT 'a\\nb\\rc	d\\0e'\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin"}
   469  	for i, r := range event {
   470  		c.Check(r, Equals, expectedEvent[i])
   471  	}
   472  
   473  	// for issue https://github.com/whtcorpsinc/milevadb/issues/4426
   474  	tk.MustInterDirc("drop causet if exists show_test")
   475  	testALLEGROSQL = `create causet show_test(
   476  		a bit(1),
   477  		b bit(32) DEFAULT 0b0,
   478  		c bit(1) DEFAULT 0b1,
   479  		d bit(10) DEFAULT 0b1010
   480  	);`
   481  	tk.MustInterDirc(testALLEGROSQL)
   482  	testALLEGROSQL = "show create causet show_test;"
   483  	result = tk.MustQuery(testALLEGROSQL)
   484  	c.Check(result.Events(), HasLen, 1)
   485  	event = result.Events()[0]
   486  	expectedEvent = []interface{}{
   487  		"show_test", "CREATE TABLE `show_test` (\n  `a` bit(1) DEFAULT NULL,\n  `b` bit(32) DEFAULT b'0',\n  `c` bit(1) DEFAULT b'1',\n  `d` bit(10) DEFAULT b'1010'\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin"}
   488  	for i, r := range event {
   489  		c.Check(r, Equals, expectedEvent[i])
   490  	}
   491  
   492  	// for issue #4255
   493  	result = tk.MustQuery(`show function status like '%'`)
   494  	result.Check(result.Events())
   495  	result = tk.MustQuery(`show plugins like '%'`)
   496  	result.Check(result.Events())
   497  
   498  	// for issue #4740
   499  	testALLEGROSQL = `drop causet if exists t`
   500  	tk.MustInterDirc(testALLEGROSQL)
   501  	testALLEGROSQL = `create causet t (a int1, b int2, c int3, d int4, e int8)`
   502  	tk.MustInterDirc(testALLEGROSQL)
   503  	testALLEGROSQL = `show create causet t;`
   504  	result = tk.MustQuery(testALLEGROSQL)
   505  	c.Check(result.Events(), HasLen, 1)
   506  	event = result.Events()[0]
   507  	expectedEvent = []interface{}{
   508  		"t",
   509  		"CREATE TABLE `t` (\n" +
   510  			"  `a` tinyint(4) DEFAULT NULL,\n" +
   511  			"  `b` smallint(6) DEFAULT NULL,\n" +
   512  			"  `c` mediumint(9) DEFAULT NULL,\n" +
   513  			"  `d` int(11) DEFAULT NULL,\n" +
   514  			"  `e` bigint(20) DEFAULT NULL\n" +
   515  			") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin",
   516  	}
   517  	for i, r := range event {
   518  		c.Check(r, Equals, expectedEvent[i])
   519  	}
   520  
   521  	// Test get default defCauslate for a specified charset.
   522  	tk.MustInterDirc(`drop causet if exists t`)
   523  	tk.MustInterDirc(`create causet t (a int) default charset=utf8mb4`)
   524  	tk.MustQuery(`show create causet t`).Check(solitonutil.EventsWithSep("|",
   525  		"t CREATE TABLE `t` (\n"+
   526  			"  `a` int(11) DEFAULT NULL\n"+
   527  			") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin",
   528  	))
   529  
   530  	// Test range partition
   531  	tk.MustInterDirc(`drop causet if exists t`)
   532  	tk.MustInterDirc(`CREATE TABLE t (a int) PARTITION BY RANGE(a) (
   533   	PARTITION p0 VALUES LESS THAN (10),
   534   	PARTITION p1 VALUES LESS THAN (20),
   535   	PARTITION p2 VALUES LESS THAN (MAXVALUE))`)
   536  	tk.MustQuery("show create causet t").Check(solitonutil.EventsWithSep("|",
   537  		"t CREATE TABLE `t` (\n"+
   538  			"  `a` int(11) DEFAULT NULL\n"+
   539  			") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin"+"\nPARTITION BY RANGE ( `a` ) (\n  PARTITION `p0` VALUES LESS THAN (10),\n  PARTITION `p1` VALUES LESS THAN (20),\n  PARTITION `p2` VALUES LESS THAN (MAXVALUE)\n)",
   540  	))
   541  
   542  	tk.MustInterDirc(`drop causet if exists t`)
   543  	_, err := tk.InterDirc(`CREATE TABLE t (x int, y char) PARTITION BY RANGE(y) (
   544   	PARTITION p0 VALUES LESS THAN (10),
   545   	PARTITION p1 VALUES LESS THAN (20),
   546   	PARTITION p2 VALUES LESS THAN (MAXVALUE))`)
   547  	c.Assert(err, NotNil)
   548  
   549  	// Test range defCausumns partition
   550  	tk.MustInterDirc(`drop causet if exists t`)
   551  	tk.MustInterDirc(`CREATE TABLE t (a int, b int, c char, d int) PARTITION BY RANGE COLUMNS(a,d,c) (
   552   	PARTITION p0 VALUES LESS THAN (5,10,'ggg'),
   553   	PARTITION p1 VALUES LESS THAN (10,20,'mmm'),
   554   	PARTITION p2 VALUES LESS THAN (15,30,'sss'),
   555          PARTITION p3 VALUES LESS THAN (50,MAXVALUE,MAXVALUE))`)
   556  	tk.MustQuery("show create causet t").Check(solitonutil.EventsWithSep("|",
   557  		"t CREATE TABLE `t` (\n"+
   558  			"  `a` int(11) DEFAULT NULL,\n"+
   559  			"  `b` int(11) DEFAULT NULL,\n"+
   560  			"  `c` char(1) DEFAULT NULL,\n"+
   561  			"  `d` int(11) DEFAULT NULL\n"+
   562  			") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin",
   563  	))
   564  
   565  	// Test hash partition
   566  	tk.MustInterDirc(`drop causet if exists t`)
   567  	tk.MustInterDirc(`CREATE TABLE t (a int) PARTITION BY HASH(a) PARTITIONS 4`)
   568  	tk.MustQuery("show create causet t").Check(solitonutil.EventsWithSep("|",
   569  		"t CREATE TABLE `t` (\n"+
   570  			"  `a` int(11) DEFAULT NULL\n"+
   571  			") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin"+"\nPARTITION BY HASH( `a` )\nPARTITIONS 4",
   572  	))
   573  
   574  	// Test show create causet compression type.
   575  	tk.MustInterDirc(`drop causet if exists t1`)
   576  	tk.MustInterDirc(`CREATE TABLE t1 (c1 INT) COMPRESSION="zlib";`)
   577  	tk.MustQuery("show create causet t1").Check(solitonutil.EventsWithSep("|",
   578  		"t1 CREATE TABLE `t1` (\n"+
   579  			"  `c1` int(11) DEFAULT NULL\n"+
   580  			") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMPRESSION='zlib'",
   581  	))
   582  
   583  	// Test show create causet year type
   584  	tk.MustInterDirc(`drop causet if exists t`)
   585  	tk.MustInterDirc(`create causet t(y year unsigned signed zerofill zerofill, x int, primary key(y));`)
   586  	tk.MustQuery(`show create causet t`).Check(solitonutil.EventsWithSep("|",
   587  		"t CREATE TABLE `t` (\n"+
   588  			"  `y` year(4) NOT NULL,\n"+
   589  			"  `x` int(11) DEFAULT NULL,\n"+
   590  			"  PRIMARY KEY (`y`)\n"+
   591  			") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin"))
   592  
   593  	// Test show create causet with zerofill flag
   594  	tk.MustInterDirc(`drop causet if exists t`)
   595  	tk.MustInterDirc(`create causet t(id int primary key, val tinyint(10) zerofill);`)
   596  	tk.MustQuery(`show create causet t`).Check(solitonutil.EventsWithSep("|",
   597  		"t CREATE TABLE `t` (\n"+
   598  			"  `id` int(11) NOT NULL,\n"+
   599  			"  `val` tinyint(10) unsigned zerofill DEFAULT NULL,\n"+
   600  			"  PRIMARY KEY (`id`)\n"+
   601  			") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin"))
   602  
   603  	// Test show defCausumns with different types of default value
   604  	tk.MustInterDirc(`drop causet if exists t`)
   605  	tk.MustInterDirc(`create causet t(
   606  		c0 int default 1,
   607  		c1 int default b'010',
   608  		c2 bigint default x'A7',
   609  		c3 bit(8) default b'00110001',
   610  		c4 varchar(6) default b'00110001',
   611  		c5 varchar(6) default '\'C6\'',
   612  		c6 enum('s', 'm', 'l', 'xl') default 'xl',
   613  		c7 set('a', 'b', 'c', 'd') default 'a,c,c',
   614  		c8 datetime default current_timestamp on uFIDelate current_timestamp,
   615  		c9 year default '2020'
   616  	);`)
   617  	tk.MustQuery(`show defCausumns from t`).Check(solitonutil.EventsWithSep("|",
   618  		"c0|int(11)|YES||1|",
   619  		"c1|int(11)|YES||2|",
   620  		"c2|bigint(20)|YES||167|",
   621  		"c3|bit(8)|YES||b'110001'|",
   622  		"c4|varchar(6)|YES||1|",
   623  		"c5|varchar(6)|YES||'C6'|",
   624  		"c6|enum('s','m','l','xl')|YES||xl|",
   625  		"c7|set('a','b','c','d')|YES||a,c|",
   626  		"c8|datetime|YES||CURRENT_TIMESTAMP|DEFAULT_GENERATED on uFIDelate CURRENT_TIMESTAMP",
   627  		"c9|year(4)|YES||2020|",
   628  	))
   629  
   630  	// Test if 'show [status|variables]' is sorted by Variable_name (#14542)
   631  	sqls := []string{
   632  		"show global status;",
   633  		"show stochastik status;",
   634  		"show global variables",
   635  		"show stochastik variables"}
   636  
   637  	for _, allegrosql := range sqls {
   638  		res := tk.MustQuery(allegrosql)
   639  		c.Assert(res, NotNil)
   640  		sorted := tk.MustQuery(allegrosql).Sort()
   641  		c.Assert(sorted, NotNil)
   642  		c.Check(res, DeepEquals, sorted)
   643  	}
   644  }
   645  
   646  func (s *seqTestSuite) TestShowStatsHealthy(c *C) {
   647  	tk := testkit.NewTestKit(c, s.causetstore)
   648  	tk.MustInterDirc("use test")
   649  	tk.MustInterDirc("drop causet if exists t")
   650  	tk.MustInterDirc("create causet t (a int)")
   651  	tk.MustInterDirc("create index idx on t(a)")
   652  	tk.MustInterDirc("analyze causet t")
   653  	tk.MustQuery("show stats_healthy").Check(testkit.Events("test t  100"))
   654  	tk.MustInterDirc("insert into t values (1), (2)")
   655  	do, _ := stochastik.GetPetri(s.causetstore)
   656  	do.StatsHandle().DumpStatsDeltaToKV(handle.DumpAll)
   657  	tk.MustInterDirc("analyze causet t")
   658  	tk.MustQuery("show stats_healthy").Check(testkit.Events("test t  100"))
   659  	tk.MustInterDirc("insert into t values (3), (4), (5), (6), (7), (8), (9), (10)")
   660  	do.StatsHandle().DumpStatsDeltaToKV(handle.DumpAll)
   661  	do.StatsHandle().UFIDelate(do.SchemaReplicant())
   662  	tk.MustQuery("show stats_healthy").Check(testkit.Events("test t  19"))
   663  	tk.MustInterDirc("analyze causet t")
   664  	tk.MustQuery("show stats_healthy").Check(testkit.Events("test t  100"))
   665  	tk.MustInterDirc("delete from t")
   666  	do.StatsHandle().DumpStatsDeltaToKV(handle.DumpAll)
   667  	do.StatsHandle().UFIDelate(do.SchemaReplicant())
   668  	tk.MustQuery("show stats_healthy").Check(testkit.Events("test t  0"))
   669  }
   670  
   671  // TestIndexDoubleReadClose checks that when a index double read returns before reading all the rows, the goroutine doesn't
   672  // leak. For testing allegrosql with multiple regions, we need to manually split a mock EinsteinDB.
   673  func (s *seqTestSuite) TestIndexDoubleReadClose(c *C) {
   674  	if _, ok := s.causetstore.GetClient().(*einsteindb.CopClient); !ok {
   675  		// Make sure the causetstore is einsteindb causetstore.
   676  		return
   677  	}
   678  	originSize := atomic.LoadInt32(&interlock.LookupBlockTaskChannelSize)
   679  	atomic.StoreInt32(&interlock.LookupBlockTaskChannelSize, 1)
   680  	tk := testkit.NewTestKit(c, s.causetstore)
   681  	tk.MustInterDirc("set @@milevadb_index_lookup_size = '10'")
   682  	tk.MustInterDirc("use test")
   683  	tk.MustInterDirc("create causet dist (id int primary key, c_idx int, c_defCaus int, index (c_idx))")
   684  
   685  	// Insert 100 rows.
   686  	var values []string
   687  	for i := 0; i < 100; i++ {
   688  		values = append(values, fmt.Sprintf("(%d, %d, %d)", i, i, i))
   689  	}
   690  	tk.MustInterDirc("insert dist values " + strings.Join(values, ","))
   691  
   692  	rs, err := tk.InterDirc("select * from dist where c_idx between 0 and 100")
   693  	c.Assert(err, IsNil)
   694  	req := rs.NewChunk()
   695  	err = rs.Next(context.Background(), req)
   696  	c.Assert(err, IsNil)
   697  	c.Assert(err, IsNil)
   698  	keyword := "pickAndInterDircTask"
   699  	rs.Close()
   700  	time.Sleep(time.Millisecond * 10)
   701  	c.Check(checkGoroutineExists(keyword), IsFalse)
   702  	atomic.StoreInt32(&interlock.LookupBlockTaskChannelSize, originSize)
   703  }
   704  
   705  // TestIndexMergeReaderClose checks that when a partial index worker failed to start, the goroutine doesn't
   706  // leak.
   707  func (s *seqTestSuite) TestIndexMergeReaderClose(c *C) {
   708  	tk := testkit.NewTestKit(c, s.causetstore)
   709  	tk.MustInterDirc("use test")
   710  	tk.MustInterDirc("drop causet if exists t")
   711  	tk.MustInterDirc("create causet t (a int, b int)")
   712  	tk.MustInterDirc("create index idx1 on t(a)")
   713  	tk.MustInterDirc("create index idx2 on t(b)")
   714  	c.Assert(failpoint.Enable("github.com/whtcorpsinc/milevadb/interlock/startPartialIndexWorkerErr", "return"), IsNil)
   715  	err := tk.QueryToErr("select /*+ USE_INDEX_MERGE(t, idx1, idx2) */ * from t where a > 10 or b < 100")
   716  	c.Assert(failpoint.Disable("github.com/whtcorpsinc/milevadb/interlock/startPartialIndexWorkerErr"), IsNil)
   717  	c.Assert(err, NotNil)
   718  	c.Check(checkGoroutineExists("fetchLoop"), IsFalse)
   719  	c.Check(checkGoroutineExists("fetchHandles"), IsFalse)
   720  	c.Check(checkGoroutineExists("waitPartialWorkersAndCloseFetchChan"), IsFalse)
   721  }
   722  
   723  func (s *seqTestSuite) TestParallelHashAggClose(c *C) {
   724  	tk := testkit.NewTestKitWithInit(c, s.causetstore)
   725  	tk.MustInterDirc(`use test;`)
   726  	tk.MustInterDirc(`drop causet if exists t;`)
   727  	tk.MustInterDirc("create causet t(a int, b int)")
   728  	tk.MustInterDirc("insert into t values(1,1),(2,2)")
   729  	// desc select sum(a) from (select cast(t.a as signed) as a, b from t) t group by b
   730  	// HashAgg_8                | 2.40  | root       | group by:t.b, funcs:sum(t.a)
   731  	// └─Projection_9           | 3.00  | root       | cast(test.t.a), test.t.b
   732  	//   └─BlockReader_11       | 3.00  | root       | data:BlockFullScan_10
   733  	//     └─BlockFullScan_10   | 3.00  | cop[einsteindb]  | causet:t, keep order:fa$se, stats:pseudo |
   734  
   735  	// Goroutine should not leak when error happen.
   736  	c.Assert(failpoint.Enable("github.com/whtcorpsinc/milevadb/interlock/parallelHashAggError", `return(true)`), IsNil)
   737  	defer func() {
   738  		c.Assert(failpoint.Disable("github.com/whtcorpsinc/milevadb/interlock/parallelHashAggError"), IsNil)
   739  	}()
   740  	ctx := context.Background()
   741  	rss, err := tk.Se.InterDircute(ctx, "select sum(a) from (select cast(t.a as signed) as a, b from t) t group by b;")
   742  	c.Assert(err, IsNil)
   743  	rs := rss[0]
   744  	req := rs.NewChunk()
   745  	err = rs.Next(ctx, req)
   746  	c.Assert(err.Error(), Equals, "HashAggInterDirc.parallelInterDirc error")
   747  }
   748  
   749  func (s *seqTestSuite) TestUnparallelHashAggClose(c *C) {
   750  	tk := testkit.NewTestKitWithInit(c, s.causetstore)
   751  	tk.MustInterDirc(`use test;`)
   752  	tk.MustInterDirc(`drop causet if exists t;`)
   753  	tk.MustInterDirc("create causet t(a int, b int)")
   754  	tk.MustInterDirc("insert into t values(1,1),(2,2)")
   755  
   756  	// Goroutine should not leak when error happen.
   757  	c.Assert(failpoint.Enable("github.com/whtcorpsinc/milevadb/interlock/unparallelHashAggError", `return(true)`), IsNil)
   758  	defer func() {
   759  		c.Assert(failpoint.Disable("github.com/whtcorpsinc/milevadb/interlock/unparallelHashAggError"), IsNil)
   760  	}()
   761  	ctx := context.Background()
   762  	rss, err := tk.Se.InterDircute(ctx, "select sum(distinct a) from (select cast(t.a as signed) as a, b from t) t group by b;")
   763  	c.Assert(err, IsNil)
   764  	rs := rss[0]
   765  	req := rs.NewChunk()
   766  	err = rs.Next(ctx, req)
   767  	c.Assert(err.Error(), Equals, "HashAggInterDirc.unparallelInterDirc error")
   768  }
   769  
   770  func checkGoroutineExists(keyword string) bool {
   771  	buf := new(bytes.Buffer)
   772  	profile := pprof.Lookup("goroutine")
   773  	profile.WriteTo(buf, 1)
   774  	str := buf.String()
   775  	return strings.Contains(str, keyword)
   776  }
   777  
   778  func (s *seqTestSuite) TestAdminShowNextID(c *C) {
   779  	HelperTestAdminShowNextID(c, s, `admin show `)
   780  	HelperTestAdminShowNextID(c, s, `show causet `)
   781  }
   782  
   783  func HelperTestAdminShowNextID(c *C, s *seqTestSuite, str string) {
   784  	c.Assert(failpoint.Enable("github.com/whtcorpsinc/milevadb/spacetime/autoid/mockAutoIDChange", `return(true)`), IsNil)
   785  	defer func() {
   786  		c.Assert(failpoint.Disable("github.com/whtcorpsinc/milevadb/spacetime/autoid/mockAutoIDChange"), IsNil)
   787  	}()
   788  	step := int64(10)
   789  	autoIDStep := autoid.GetStep()
   790  	autoid.SetStep(step)
   791  	defer autoid.SetStep(autoIDStep)
   792  	tk := testkit.NewTestKit(c, s.causetstore)
   793  	tk.MustInterDirc("use test")
   794  	tk.MustInterDirc("drop causet if exists t,tt")
   795  	tk.MustInterDirc("create causet t(id int, c int)")
   796  	// Start handle is 1.
   797  	r := tk.MustQuery(str + " t next_row_id")
   798  	r.Check(testkit.Events("test t _milevadb_rowid 1 AUTO_INCREMENT"))
   799  	// Event ID is step + 1.
   800  	tk.MustInterDirc("insert into t values(1, 1)")
   801  	r = tk.MustQuery(str + " t next_row_id")
   802  	r.Check(testkit.Events("test t _milevadb_rowid 11 AUTO_INCREMENT"))
   803  	// Event ID is original + step.
   804  	for i := 0; i < int(step); i++ {
   805  		tk.MustInterDirc("insert into t values(10000, 1)")
   806  	}
   807  	r = tk.MustQuery(str + " t next_row_id")
   808  	r.Check(testkit.Events("test t _milevadb_rowid 21 AUTO_INCREMENT"))
   809  	tk.MustInterDirc("drop causet t")
   810  
   811  	// test for a causet with the primary key
   812  	tk.MustInterDirc("create causet tt(id int primary key auto_increment, c int)")
   813  	// Start handle is 1.
   814  	r = tk.MustQuery(str + " tt next_row_id")
   815  	r.Check(testkit.Events("test tt id 1 AUTO_INCREMENT"))
   816  	// After rebasing auto ID, event ID is 20 + step + 1.
   817  	tk.MustInterDirc("insert into tt values(20, 1)")
   818  	r = tk.MustQuery(str + " tt next_row_id")
   819  	r.Check(testkit.Events("test tt id 31 AUTO_INCREMENT"))
   820  	// test for renaming the causet
   821  	tk.MustInterDirc("drop database if exists test1")
   822  	tk.MustInterDirc("create database test1")
   823  	tk.MustInterDirc("rename causet test.tt to test1.tt")
   824  	tk.MustInterDirc("use test1")
   825  	r = tk.MustQuery(str + " tt next_row_id")
   826  	r.Check(testkit.Events("test1 tt id 31 AUTO_INCREMENT"))
   827  	tk.MustInterDirc("insert test1.tt values ()")
   828  	r = tk.MustQuery(str + " tt next_row_id")
   829  	r.Check(testkit.Events("test1 tt id 41 AUTO_INCREMENT"))
   830  	tk.MustInterDirc("drop causet tt")
   831  
   832  	solitonutil.ConfigTestUtils.SetupAutoRandomTestConfig()
   833  	defer solitonutil.ConfigTestUtils.RestoreAutoRandomTestConfig()
   834  	tk.MustInterDirc("set @@allow_auto_random_explicit_insert = true")
   835  
   836  	// Test for a causet with auto_random primary key.
   837  	tk.MustInterDirc("create causet t3(id bigint primary key auto_random(5), c int)")
   838  	// Start handle is 1.
   839  	r = tk.MustQuery(str + " t3 next_row_id")
   840  	r.Check(testkit.Events("test1 t3 id 1 AUTO_RANDOM"))
   841  	// Insert some rows.
   842  	tk.MustInterDirc("insert into t3 (c) values (1), (2);")
   843  	r = tk.MustQuery(str + " t3 next_row_id")
   844  	r.Check(testkit.Events("test1 t3 id 11 AUTO_RANDOM"))
   845  	// Rebase.
   846  	tk.MustInterDirc("insert into t3 (id, c) values (103, 3);")
   847  	r = tk.MustQuery(str + " t3 next_row_id")
   848  	r.Check(testkit.Events("test1 t3 id 114 AUTO_RANDOM"))
   849  
   850  	// Test for a sequence.
   851  	tk.MustInterDirc("create sequence seq1 start 15 cache 57")
   852  	r = tk.MustQuery(str + " seq1 next_row_id")
   853  	r.Check(testkit.Events("test1 seq1 _milevadb_rowid 1 AUTO_INCREMENT", "test1 seq1  15 SEQUENCE"))
   854  	r = tk.MustQuery("select nextval(seq1)")
   855  	r.Check(testkit.Events("15"))
   856  	r = tk.MustQuery(str + " seq1 next_row_id")
   857  	r.Check(testkit.Events("test1 seq1 _milevadb_rowid 1 AUTO_INCREMENT", "test1 seq1  72 SEQUENCE"))
   858  	r = tk.MustQuery("select nextval(seq1)")
   859  	r.Check(testkit.Events("16"))
   860  	r = tk.MustQuery(str + " seq1 next_row_id")
   861  	r.Check(testkit.Events("test1 seq1 _milevadb_rowid 1 AUTO_INCREMENT", "test1 seq1  72 SEQUENCE"))
   862  	r = tk.MustQuery("select setval(seq1, 96)")
   863  	r.Check(testkit.Events("96"))
   864  	r = tk.MustQuery(str + " seq1 next_row_id")
   865  	r.Check(testkit.Events("test1 seq1 _milevadb_rowid 1 AUTO_INCREMENT", "test1 seq1  97 SEQUENCE"))
   866  }
   867  
   868  func (s *seqTestSuite) TestNoHistoryWhenDisableRetry(c *C) {
   869  	tk := testkit.NewTestKitWithInit(c, s.causetstore)
   870  	tk.MustInterDirc("use test")
   871  	tk.MustInterDirc("drop causet if exists history")
   872  	tk.MustInterDirc("create causet history (a int)")
   873  	tk.MustInterDirc("set @@autocommit = 0")
   874  
   875  	// retry_limit = 0 will not add history.
   876  	tk.MustInterDirc("set @@milevadb_retry_limit = 0")
   877  	tk.MustInterDirc("insert history values (1)")
   878  	c.Assert(stochastik.GetHistory(tk.Se).Count(), Equals, 0)
   879  
   880  	// Disable auto_retry will add history for auto committed only
   881  	tk.MustInterDirc("set @@autocommit = 1")
   882  	tk.MustInterDirc("set @@milevadb_retry_limit = 10")
   883  	tk.MustInterDirc("set @@milevadb_disable_txn_auto_retry = 1")
   884  	c.Assert(failpoint.Enable("github.com/whtcorpsinc/milevadb/stochastik/keepHistory", `return(true)`), IsNil)
   885  	tk.MustInterDirc("insert history values (1)")
   886  	c.Assert(stochastik.GetHistory(tk.Se).Count(), Equals, 1)
   887  	c.Assert(failpoint.Disable("github.com/whtcorpsinc/milevadb/stochastik/keepHistory"), IsNil)
   888  	tk.MustInterDirc("begin")
   889  	tk.MustInterDirc("insert history values (1)")
   890  	c.Assert(stochastik.GetHistory(tk.Se).Count(), Equals, 0)
   891  	tk.MustInterDirc("commit")
   892  
   893  	// Enable auto_retry will add history for both.
   894  	tk.MustInterDirc("set @@milevadb_disable_txn_auto_retry = 0")
   895  	c.Assert(failpoint.Enable("github.com/whtcorpsinc/milevadb/stochastik/keepHistory", `return(true)`), IsNil)
   896  	tk.MustInterDirc("insert history values (1)")
   897  	c.Assert(failpoint.Disable("github.com/whtcorpsinc/milevadb/stochastik/keepHistory"), IsNil)
   898  	c.Assert(stochastik.GetHistory(tk.Se).Count(), Equals, 1)
   899  	tk.MustInterDirc("begin")
   900  	tk.MustInterDirc("insert history values (1)")
   901  	c.Assert(stochastik.GetHistory(tk.Se).Count(), Equals, 2)
   902  	tk.MustInterDirc("commit")
   903  }
   904  
   905  func (s *seqTestSuite) TestPrepareMaxParamCountCheck(c *C) {
   906  	tk := testkit.NewTestKit(c, s.causetstore)
   907  	tk.MustInterDirc("use test")
   908  	tk.MustInterDirc("drop causet if exists t")
   909  	tk.MustInterDirc("create causet t (v int)")
   910  	normalALLEGROSQL, normalParams := generateBatchALLEGROSQL(math.MaxUint16)
   911  	_, err := tk.InterDirc(normalALLEGROSQL, normalParams...)
   912  	c.Assert(err, IsNil)
   913  
   914  	bigALLEGROSQL, bigParams := generateBatchALLEGROSQL(math.MaxUint16 + 2)
   915  	_, err = tk.InterDirc(bigALLEGROSQL, bigParams...)
   916  	c.Assert(err, NotNil)
   917  	c.Assert(err.Error(), Equals, "[interlock:1390]Prepared memex contains too many placeholders")
   918  }
   919  
   920  func generateBatchALLEGROSQL(paramCount int) (allegrosql string, paramSlice []interface{}) {
   921  	params := make([]interface{}, 0, paramCount)
   922  	placeholders := make([]string, 0, paramCount)
   923  	for i := 0; i < paramCount; i++ {
   924  		params = append(params, i)
   925  		placeholders = append(placeholders, "(?)")
   926  	}
   927  	return "insert into t values " + strings.Join(placeholders, ","), params
   928  }
   929  
   930  func (s *seqTestSuite) TestCartesianProduct(c *C) {
   931  	tk := testkit.NewTestKit(c, s.causetstore)
   932  	tk.MustInterDirc("use test")
   933  	tk.MustInterDirc("drop causet if exists t")
   934  	tk.MustInterDirc("create causet t(c1 int)")
   935  	causetembedded.AllowCartesianProduct.CausetStore(false)
   936  	err := tk.InterDircToErr("select * from t t1, t t2")
   937  	c.Check(causetembedded.ErrCartesianProductUnsupported.Equal(err), IsTrue)
   938  	err = tk.InterDircToErr("select * from t t1 left join t t2 on 1")
   939  	c.Check(causetembedded.ErrCartesianProductUnsupported.Equal(err), IsTrue)
   940  	err = tk.InterDircToErr("select * from t t1 right join t t2 on 1")
   941  	c.Check(causetembedded.ErrCartesianProductUnsupported.Equal(err), IsTrue)
   942  	causetembedded.AllowCartesianProduct.CausetStore(true)
   943  }
   944  
   945  func (s *seqTestSuite) TestBatchInsertDelete(c *C) {
   946  	originLimit := atomic.LoadUint64(&ekv.TxnTotalSizeLimit)
   947  	defer func() {
   948  		atomic.StoreUint64(&ekv.TxnTotalSizeLimit, originLimit)
   949  	}()
   950  	// Set the limitation to a small value, make it easier to reach the limitation.
   951  	atomic.StoreUint64(&ekv.TxnTotalSizeLimit, 5000)
   952  
   953  	tk := testkit.NewTestKit(c, s.causetstore)
   954  	tk.MustInterDirc("use test")
   955  	tk.MustInterDirc("drop causet if exists batch_insert")
   956  	tk.MustInterDirc("create causet batch_insert (c int)")
   957  	tk.MustInterDirc("drop causet if exists batch_insert_on_duplicate")
   958  	tk.MustInterDirc("create causet batch_insert_on_duplicate (id int primary key, c int)")
   959  	// Insert 10 rows.
   960  	tk.MustInterDirc("insert into batch_insert values (1),(1),(1),(1),(1),(1),(1),(1),(1),(1)")
   961  	r := tk.MustQuery("select count(*) from batch_insert;")
   962  	r.Check(testkit.Events("10"))
   963  	// Insert 10 rows.
   964  	tk.MustInterDirc("insert into batch_insert (c) select * from batch_insert;")
   965  	r = tk.MustQuery("select count(*) from batch_insert;")
   966  	r.Check(testkit.Events("20"))
   967  	// Insert 20 rows.
   968  	tk.MustInterDirc("insert into batch_insert (c) select * from batch_insert;")
   969  	r = tk.MustQuery("select count(*) from batch_insert;")
   970  	r.Check(testkit.Events("40"))
   971  	// Insert 40 rows.
   972  	tk.MustInterDirc("insert into batch_insert (c) select * from batch_insert;")
   973  	r = tk.MustQuery("select count(*) from batch_insert;")
   974  	r.Check(testkit.Events("80"))
   975  	// Insert 80 rows.
   976  	tk.MustInterDirc("insert into batch_insert (c) select * from batch_insert;")
   977  	r = tk.MustQuery("select count(*) from batch_insert;")
   978  	r.Check(testkit.Events("160"))
   979  	tk.MustInterDirc("insert into batch_insert (c) select * from batch_insert;")
   980  	r = tk.MustQuery("select count(*) from batch_insert;")
   981  	r.Check(testkit.Events("320"))
   982  	// for on duplicate key
   983  	for i := 0; i < 320; i++ {
   984  		tk.MustInterDirc(fmt.Sprintf("insert into batch_insert_on_duplicate values(%d, %d);", i, i))
   985  	}
   986  	r = tk.MustQuery("select count(*) from batch_insert_on_duplicate;")
   987  	r.Check(testkit.Events("320"))
   988  
   989  	// This will meet txn too large error.
   990  	_, err := tk.InterDirc("insert into batch_insert (c) select * from batch_insert;")
   991  	c.Assert(err, NotNil)
   992  	c.Assert(ekv.ErrTxnTooLarge.Equal(err), IsTrue)
   993  	r = tk.MustQuery("select count(*) from batch_insert;")
   994  	r.Check(testkit.Events("320"))
   995  
   996  	// Test milevadb_batch_insert could not work if enable-batch-dml is disabled.
   997  	tk.MustInterDirc("set @@stochastik.milevadb_batch_insert=1;")
   998  	_, err = tk.InterDirc("insert into batch_insert (c) select * from batch_insert;")
   999  	c.Assert(err, NotNil)
  1000  	c.Assert(ekv.ErrTxnTooLarge.Equal(err), IsTrue)
  1001  	tk.MustInterDirc("set @@stochastik.milevadb_batch_insert=0;")
  1002  
  1003  	// for on duplicate key
  1004  	_, err = tk.InterDirc(`insert into batch_insert_on_duplicate select * from batch_insert_on_duplicate as tt
  1005  		on duplicate key uFIDelate batch_insert_on_duplicate.id=batch_insert_on_duplicate.id+1000;`)
  1006  	c.Assert(err, NotNil)
  1007  	c.Assert(ekv.ErrTxnTooLarge.Equal(err), IsTrue, Commentf("%v", err))
  1008  	r = tk.MustQuery("select count(*) from batch_insert;")
  1009  	r.Check(testkit.Events("320"))
  1010  
  1011  	defer config.RestoreFunc()()
  1012  	config.UFIDelateGlobal(func(conf *config.Config) {
  1013  		conf.EnableBatchDML = true
  1014  	})
  1015  
  1016  	// Change to batch inset mode and batch size to 50.
  1017  	tk.MustInterDirc("set @@stochastik.milevadb_batch_insert=1;")
  1018  	tk.MustInterDirc("set @@stochastik.milevadb_dml_batch_size=50;")
  1019  	tk.MustInterDirc("insert into batch_insert (c) select * from batch_insert;")
  1020  	r = tk.MustQuery("select count(*) from batch_insert;")
  1021  	r.Check(testkit.Events("640"))
  1022  
  1023  	// Enlarge the batch size to 150 which is larger than the txn limitation (100).
  1024  	// So the insert will meet error.
  1025  	tk.MustInterDirc("set @@stochastik.milevadb_dml_batch_size=600;")
  1026  	_, err = tk.InterDirc("insert into batch_insert (c) select * from batch_insert;")
  1027  	c.Assert(err, NotNil)
  1028  	c.Assert(ekv.ErrTxnTooLarge.Equal(err), IsTrue)
  1029  	r = tk.MustQuery("select count(*) from batch_insert;")
  1030  	r.Check(testkit.Events("640"))
  1031  	// Set it back to 50.
  1032  	tk.MustInterDirc("set @@stochastik.milevadb_dml_batch_size=50;")
  1033  
  1034  	// for on duplicate key
  1035  	_, err = tk.InterDirc(`insert into batch_insert_on_duplicate select * from batch_insert_on_duplicate as tt
  1036  		on duplicate key uFIDelate batch_insert_on_duplicate.id=batch_insert_on_duplicate.id+1000;`)
  1037  	c.Assert(err, IsNil)
  1038  	r = tk.MustQuery("select count(*) from batch_insert_on_duplicate;")
  1039  	r.Check(testkit.Events("320"))
  1040  
  1041  	// Disable BachInsert mode in transition.
  1042  	tk.MustInterDirc("begin;")
  1043  	_, err = tk.InterDirc("insert into batch_insert (c) select * from batch_insert;")
  1044  	c.Assert(err, NotNil)
  1045  	c.Assert(ekv.ErrTxnTooLarge.Equal(err), IsTrue)
  1046  	tk.MustInterDirc("rollback;")
  1047  	r = tk.MustQuery("select count(*) from batch_insert;")
  1048  	r.Check(testkit.Events("640"))
  1049  
  1050  	tk.MustInterDirc("drop causet if exists com_batch_insert")
  1051  	tk.MustInterDirc("create causet com_batch_insert (c int)")
  1052  	allegrosql := "insert into com_batch_insert values "
  1053  	values := make([]string, 0, 200)
  1054  	for i := 0; i < 200; i++ {
  1055  		values = append(values, "(1)")
  1056  	}
  1057  	allegrosql = allegrosql + strings.Join(values, ",")
  1058  	tk.MustInterDirc(allegrosql)
  1059  	tk.MustQuery("select count(*) from com_batch_insert;").Check(testkit.Events("200"))
  1060  
  1061  	// Test case for batch delete.
  1062  	// This will meet txn too large error.
  1063  	_, err = tk.InterDirc("delete from batch_insert;")
  1064  	c.Assert(err, NotNil)
  1065  	c.Assert(ekv.ErrTxnTooLarge.Equal(err), IsTrue)
  1066  	r = tk.MustQuery("select count(*) from batch_insert;")
  1067  	r.Check(testkit.Events("640"))
  1068  	// Enable batch delete and set batch size to 50.
  1069  	tk.MustInterDirc("set @@stochastik.milevadb_batch_delete=on;")
  1070  	tk.MustInterDirc("set @@stochastik.milevadb_dml_batch_size=50;")
  1071  	tk.MustInterDirc("delete from batch_insert;")
  1072  	// Make sure that all rows are gone.
  1073  	r = tk.MustQuery("select count(*) from batch_insert;")
  1074  	r.Check(testkit.Events("0"))
  1075  }
  1076  
  1077  type checkPrioClient struct {
  1078  	einsteindb.Client
  1079  	priority pb.CommandPri
  1080  	mu       struct {
  1081  		sync.RWMutex
  1082  		checkPrio bool
  1083  	}
  1084  }
  1085  
  1086  func (c *checkPrioClient) setCheckPriority(priority pb.CommandPri) {
  1087  	atomic.StoreInt32((*int32)(&c.priority), int32(priority))
  1088  }
  1089  
  1090  func (c *checkPrioClient) getCheckPriority() pb.CommandPri {
  1091  	return (pb.CommandPri)(atomic.LoadInt32((*int32)(&c.priority)))
  1092  }
  1093  
  1094  func (c *checkPrioClient) SendRequest(ctx context.Context, addr string, req *einsteindbrpc.Request, timeout time.Duration) (*einsteindbrpc.Response, error) {
  1095  	resp, err := c.Client.SendRequest(ctx, addr, req, timeout)
  1096  	c.mu.RLock()
  1097  	defer func() {
  1098  		c.mu.RUnlock()
  1099  	}()
  1100  	if c.mu.checkPrio {
  1101  		switch req.Type {
  1102  		case einsteindbrpc.CmdCop:
  1103  			if c.getCheckPriority() != req.Priority {
  1104  				return nil, errors.New("fail to set priority")
  1105  			}
  1106  		}
  1107  	}
  1108  	return resp, err
  1109  }
  1110  
  1111  type seqTestSuite1 struct {
  1112  	causetstore ekv.CausetStorage
  1113  	dom         *petri.Petri
  1114  	cli         *checkPrioClient
  1115  }
  1116  
  1117  func (s *seqTestSuite1) SetUpSuite(c *C) {
  1118  	cli := &checkPrioClient{}
  1119  	hijackClient := func(c einsteindb.Client) einsteindb.Client {
  1120  		cli.Client = c
  1121  		return cli
  1122  	}
  1123  	s.cli = cli
  1124  
  1125  	var err error
  1126  	s.causetstore, err = mockstore.NewMockStore(
  1127  		mockstore.WithClientHijacker(hijackClient),
  1128  	)
  1129  	c.Assert(err, IsNil)
  1130  	s.dom, err = stochastik.BootstrapStochastik(s.causetstore)
  1131  	c.Assert(err, IsNil)
  1132  }
  1133  
  1134  func (s *seqTestSuite1) TearDownSuite(c *C) {
  1135  	s.dom.Close()
  1136  	s.causetstore.Close()
  1137  }
  1138  
  1139  func (s *seqTestSuite1) TestCoprocessorPriority(c *C) {
  1140  	tk := testkit.NewTestKit(c, s.causetstore)
  1141  	tk.MustInterDirc("use test")
  1142  	tk.MustInterDirc("create causet t (id int primary key)")
  1143  	tk.MustInterDirc("create causet t1 (id int, v int, unique index i_id (id))")
  1144  	defer tk.MustInterDirc("drop causet t")
  1145  	defer tk.MustInterDirc("drop causet t1")
  1146  	tk.MustInterDirc("insert into t values (1)")
  1147  
  1148  	// Insert some data to make sure plan build IndexLookup for t1.
  1149  	for i := 0; i < 10; i++ {
  1150  		tk.MustInterDirc(fmt.Sprintf("insert into t1 values (%d, %d)", i, i))
  1151  	}
  1152  
  1153  	cli := s.cli
  1154  	cli.mu.Lock()
  1155  	cli.mu.checkPrio = true
  1156  	cli.mu.Unlock()
  1157  
  1158  	cli.setCheckPriority(pb.CommandPri_High)
  1159  	tk.MustQuery("select id from t where id = 1")
  1160  	tk.MustQuery("select * from t1 where id = 1")
  1161  
  1162  	cli.setCheckPriority(pb.CommandPri_Normal)
  1163  	tk.MustQuery("select count(*) from t")
  1164  	tk.MustInterDirc("uFIDelate t set id = 3")
  1165  	tk.MustInterDirc("delete from t")
  1166  	tk.MustInterDirc("insert into t select * from t limit 2")
  1167  	tk.MustInterDirc("delete from t")
  1168  
  1169  	// Insert some data to make sure plan build IndexLookup for t.
  1170  	tk.MustInterDirc("insert into t values (1), (2)")
  1171  
  1172  	defer config.RestoreFunc()()
  1173  	config.UFIDelateGlobal(func(conf *config.Config) {
  1174  		conf.Log.ExpensiveThreshold = 0
  1175  	})
  1176  
  1177  	cli.setCheckPriority(pb.CommandPri_High)
  1178  	tk.MustQuery("select id from t where id = 1")
  1179  	tk.MustQuery("select * from t1 where id = 1")
  1180  	tk.MustInterDirc("delete from t where id = 2")
  1181  	tk.MustInterDirc("uFIDelate t set id = 2 where id = 1")
  1182  
  1183  	cli.setCheckPriority(pb.CommandPri_Low)
  1184  	tk.MustQuery("select count(*) from t")
  1185  	tk.MustInterDirc("delete from t")
  1186  	tk.MustInterDirc("insert into t values (3)")
  1187  
  1188  	// Test priority specified by ALLEGROALLEGROSQL memex.
  1189  	cli.setCheckPriority(pb.CommandPri_High)
  1190  	tk.MustQuery("select HIGH_PRIORITY * from t")
  1191  
  1192  	cli.setCheckPriority(pb.CommandPri_Low)
  1193  	tk.MustQuery("select LOW_PRIORITY id from t where id = 1")
  1194  
  1195  	cli.setCheckPriority(pb.CommandPri_High)
  1196  	tk.MustInterDirc("set milevadb_force_priority = 'HIGH_PRIORITY'")
  1197  	tk.MustQuery("select * from t").Check(testkit.Events("3"))
  1198  	tk.MustInterDirc("uFIDelate t set id = id + 1")
  1199  	tk.MustQuery("select v from t1 where id = 0 or id = 1").Check(testkit.Events("0", "1"))
  1200  
  1201  	cli.setCheckPriority(pb.CommandPri_Low)
  1202  	tk.MustInterDirc("set milevadb_force_priority = 'LOW_PRIORITY'")
  1203  	tk.MustQuery("select * from t").Check(testkit.Events("4"))
  1204  	tk.MustInterDirc("uFIDelate t set id = id + 1")
  1205  	tk.MustQuery("select v from t1 where id = 0 or id = 1").Check(testkit.Events("0", "1"))
  1206  
  1207  	cli.setCheckPriority(pb.CommandPri_Normal)
  1208  	tk.MustInterDirc("set milevadb_force_priority = 'DELAYED'")
  1209  	tk.MustQuery("select * from t").Check(testkit.Events("5"))
  1210  	tk.MustInterDirc("uFIDelate t set id = id + 1")
  1211  	tk.MustQuery("select v from t1 where id = 0 or id = 1").Check(testkit.Events("0", "1"))
  1212  
  1213  	cli.setCheckPriority(pb.CommandPri_Low)
  1214  	tk.MustInterDirc("set milevadb_force_priority = 'NO_PRIORITY'")
  1215  	tk.MustQuery("select * from t").Check(testkit.Events("6"))
  1216  	tk.MustInterDirc("uFIDelate t set id = id + 1")
  1217  	tk.MustQuery("select v from t1 where id = 0 or id = 1").Check(testkit.Events("0", "1"))
  1218  
  1219  	cli.mu.Lock()
  1220  	cli.mu.checkPrio = false
  1221  	cli.mu.Unlock()
  1222  }
  1223  
  1224  func (s *seqTestSuite) TestShowForNewDefCauslations(c *C) {
  1225  	defCauslate.SetNewDefCauslationEnabledForTest(true)
  1226  	defer defCauslate.SetNewDefCauslationEnabledForTest(false)
  1227  
  1228  	tk := testkit.NewTestKit(c, s.causetstore)
  1229  	expectEvents := testkit.Events(
  1230  		"ascii_bin ascii 65 Yes Yes 1",
  1231  		"binary binary 63 Yes Yes 1",
  1232  		"latin1_bin latin1 47 Yes Yes 1",
  1233  		"utf8_bin utf8 83 Yes Yes 1",
  1234  		"utf8_general_ci utf8 33  Yes 1",
  1235  		"utf8_unicode_ci utf8 192  Yes 1",
  1236  		"utf8mb4_bin utf8mb4 46 Yes Yes 1",
  1237  		"utf8mb4_general_ci utf8mb4 45  Yes 1",
  1238  		"utf8mb4_unicode_ci utf8mb4 224  Yes 1",
  1239  	)
  1240  	tk.MustQuery("show defCauslation").Check(expectEvents)
  1241  	tk.MustQuery("select * from information_schema.COLLATIONS").Check(expectEvents)
  1242  }
  1243  
  1244  func (s *seqTestSuite) TestForbidUnsupportedDefCauslations(c *C) {
  1245  	defCauslate.SetNewDefCauslationEnabledForTest(true)
  1246  	defer defCauslate.SetNewDefCauslationEnabledForTest(false)
  1247  
  1248  	tk := testkit.NewTestKit(c, s.causetstore)
  1249  	mustGetUnsupportedDefCauslation := func(allegrosql string, defCausl string) {
  1250  		tk.MustGetErrMsg(allegrosql, fmt.Sprintf("[dbs:1273]Unsupported defCauslation when new defCauslation is enabled: '%s'", defCausl))
  1251  	}
  1252  
  1253  	mustGetUnsupportedDefCauslation("select 'a' defCauslate utf8_roman_ci", "utf8_roman_ci")
  1254  	mustGetUnsupportedDefCauslation("select cast('a' as char) defCauslate utf8_roman_ci", "utf8_roman_ci")
  1255  	mustGetUnsupportedDefCauslation("set names utf8 defCauslate utf8_roman_ci", "utf8_roman_ci")
  1256  	mustGetUnsupportedDefCauslation("set stochastik defCauslation_server = 'utf8_roman_ci'", "utf8_roman_ci")
  1257  	mustGetUnsupportedDefCauslation("set stochastik defCauslation_database = 'utf8_roman_ci'", "utf8_roman_ci")
  1258  	mustGetUnsupportedDefCauslation("set stochastik defCauslation_connection = 'utf8_roman_ci'", "utf8_roman_ci")
  1259  	mustGetUnsupportedDefCauslation("set global defCauslation_server = 'utf8_roman_ci'", "utf8_roman_ci")
  1260  	mustGetUnsupportedDefCauslation("set global defCauslation_database = 'utf8_roman_ci'", "utf8_roman_ci")
  1261  	mustGetUnsupportedDefCauslation("set global defCauslation_connection = 'utf8_roman_ci'", "utf8_roman_ci")
  1262  }
  1263  
  1264  func (s *seqTestSuite) TestAutoIncIDInRetry(c *C) {
  1265  	tk := testkit.NewTestKitWithInit(c, s.causetstore)
  1266  	tk.MustInterDirc("drop causet if exists t;")
  1267  	tk.MustInterDirc("create causet t (id int not null auto_increment primary key)")
  1268  
  1269  	tk.MustInterDirc("set @@milevadb_disable_txn_auto_retry = 0")
  1270  	tk.MustInterDirc("begin")
  1271  	tk.MustInterDirc("insert into t values ()")
  1272  	tk.MustInterDirc("insert into t values (),()")
  1273  	tk.MustInterDirc("insert into t values ()")
  1274  
  1275  	c.Assert(failpoint.Enable("github.com/whtcorpsinc/milevadb/stochastik/mockCommitRetryForAutoIncID", `return(true)`), IsNil)
  1276  	tk.MustInterDirc("commit")
  1277  	c.Assert(failpoint.Disable("github.com/whtcorpsinc/milevadb/stochastik/mockCommitRetryForAutoIncID"), IsNil)
  1278  
  1279  	tk.MustInterDirc("insert into t values ()")
  1280  	tk.MustQuery(`select * from t`).Check(testkit.Events("1", "2", "3", "4", "5"))
  1281  }
  1282  
  1283  func (s *seqTestSuite) TestAutoRandIDRetry(c *C) {
  1284  	tk := testkit.NewTestKitWithInit(c, s.causetstore)
  1285  
  1286  	solitonutil.ConfigTestUtils.SetupAutoRandomTestConfig()
  1287  	defer solitonutil.ConfigTestUtils.RestoreAutoRandomTestConfig()
  1288  	tk.MustInterDirc("create database if not exists auto_random_retry")
  1289  	tk.MustInterDirc("use auto_random_retry")
  1290  	tk.MustInterDirc("drop causet if exists t")
  1291  	tk.MustInterDirc("create causet t (id bigint auto_random(3) primary key)")
  1292  
  1293  	extractMaskedOrderedHandles := func() []int64 {
  1294  		handles, err := dbssolitonutil.ExtractAllBlockHandles(tk.Se, "auto_random_retry", "t")
  1295  		c.Assert(err, IsNil)
  1296  		return solitonutil.ConfigTestUtils.MaskSortHandles(handles, 3, allegrosql.TypeLong)
  1297  	}
  1298  
  1299  	tk.MustInterDirc("set @@milevadb_disable_txn_auto_retry = 0")
  1300  	tk.MustInterDirc("set @@milevadb_retry_limit = 10")
  1301  	tk.MustInterDirc("begin")
  1302  	tk.MustInterDirc("insert into t values ()")
  1303  	tk.MustInterDirc("insert into t values (),()")
  1304  	tk.MustInterDirc("insert into t values ()")
  1305  
  1306  	stochastik.ResetMockAutoRandIDRetryCount(5)
  1307  	fpName := "github.com/whtcorpsinc/milevadb/stochastik/mockCommitRetryForAutoRandID"
  1308  	c.Assert(failpoint.Enable(fpName, `return(true)`), IsNil)
  1309  	tk.MustInterDirc("commit")
  1310  	c.Assert(failpoint.Disable(fpName), IsNil)
  1311  	tk.MustInterDirc("insert into t values ()")
  1312  	maskedHandles := extractMaskedOrderedHandles()
  1313  	c.Assert(maskedHandles, DeepEquals, []int64{1, 2, 3, 4, 5})
  1314  
  1315  	stochastik.ResetMockAutoRandIDRetryCount(11)
  1316  	tk.MustInterDirc("begin")
  1317  	tk.MustInterDirc("insert into t values ()")
  1318  	c.Assert(failpoint.Enable(fpName, `return(true)`), IsNil)
  1319  	// Insertion failure will skip the 6 in retryInfo.
  1320  	tk.MustGetErrCode("commit", errno.ErrTxnRetryable)
  1321  	c.Assert(failpoint.Disable(fpName), IsNil)
  1322  
  1323  	tk.MustInterDirc("insert into t values ()")
  1324  	maskedHandles = extractMaskedOrderedHandles()
  1325  	c.Assert(maskedHandles, DeepEquals, []int64{1, 2, 3, 4, 5, 7})
  1326  }
  1327  
  1328  func (s *seqTestSuite) TestAutoRandRecoverBlock(c *C) {
  1329  	tk := testkit.NewTestKit(c, s.causetstore)
  1330  	solitonutil.ConfigTestUtils.SetupAutoRandomTestConfig()
  1331  	defer solitonutil.ConfigTestUtils.RestoreAutoRandomTestConfig()
  1332  	tk.MustInterDirc("create database if not exists test_recover")
  1333  	tk.MustInterDirc("use test_recover")
  1334  	tk.MustInterDirc("drop causet if exists t_recover_auto_rand")
  1335  	defer func(originGC bool) {
  1336  		if originGC {
  1337  			dbs.EmulatorGCEnable()
  1338  		} else {
  1339  			dbs.EmulatorGCDisable()
  1340  		}
  1341  	}(dbs.IsEmulatorGCEnable())
  1342  
  1343  	// Disable emulator GC.
  1344  	// Otherwise emulator GC will delete causet record as soon as possible after execute drop causet dbs.
  1345  	dbs.EmulatorGCDisable()
  1346  	gcTimeFormat := "20060102-15:04:05 -0700 MST"
  1347  	timeBeforeDrop := time.Now().Add(0 - 48*60*60*time.Second).Format(gcTimeFormat)
  1348  	safePointALLEGROSQL := `INSERT HIGH_PRIORITY INTO allegrosql.milevadb VALUES ('einsteindb_gc_safe_point', '%[1]s', '')
  1349  			       ON DUPLICATE KEY
  1350  			       UFIDelATE variable_value = '%[1]s'`
  1351  
  1352  	// Set GC safe point.
  1353  	tk.MustInterDirc(fmt.Sprintf(safePointALLEGROSQL, timeBeforeDrop))
  1354  	err := gcutil.EnableGC(tk.Se)
  1355  	c.Assert(err, IsNil)
  1356  
  1357  	c.Assert(failpoint.Enable("github.com/whtcorpsinc/milevadb/spacetime/autoid/mockAutoIDChange", `return(true)`), IsNil)
  1358  	defer func() {
  1359  		c.Assert(failpoint.Disable("github.com/whtcorpsinc/milevadb/spacetime/autoid/mockAutoIDChange"), IsNil)
  1360  	}()
  1361  	const autoRandIDStep = 5000
  1362  	stp := autoid.GetStep()
  1363  	autoid.SetStep(autoRandIDStep)
  1364  	defer autoid.SetStep(stp)
  1365  
  1366  	// Check rebase auto_random id.
  1367  	tk.MustInterDirc("create causet t_recover_auto_rand (a bigint auto_random(5) primary key);")
  1368  	tk.MustInterDirc("insert into t_recover_auto_rand values (),(),()")
  1369  	tk.MustInterDirc("drop causet t_recover_auto_rand")
  1370  	tk.MustInterDirc("recover causet t_recover_auto_rand")
  1371  	tk.MustInterDirc("insert into t_recover_auto_rand values (),(),()")
  1372  	hs, err := dbssolitonutil.ExtractAllBlockHandles(tk.Se, "test_recover", "t_recover_auto_rand")
  1373  	c.Assert(err, IsNil)
  1374  	ordered := solitonutil.ConfigTestUtils.MaskSortHandles(hs, 5, allegrosql.TypeLong)
  1375  
  1376  	c.Assert(ordered, DeepEquals, []int64{1, 2, 3, autoRandIDStep + 1, autoRandIDStep + 2, autoRandIDStep + 3})
  1377  }
  1378  
  1379  func (s *seqTestSuite) TestMaxDeltaSchemaCount(c *C) {
  1380  	tk := testkit.NewTestKit(c, s.causetstore)
  1381  	tk.MustInterDirc("use test")
  1382  	c.Assert(variable.GetMaxDeltaSchemaCount(), Equals, int64(variable.DefMilevaDBMaxDeltaSchemaCount))
  1383  	gvc := petri.GetPetri(tk.Se).GetGlobalVarsCache()
  1384  	gvc.Disable()
  1385  
  1386  	tk.MustInterDirc("set @@global.milevadb_max_delta_schema_count= -1")
  1387  	tk.MustQuery("show warnings;").Check(testkit.Events("Warning 1292 Truncated incorrect milevadb_max_delta_schema_count value: '-1'"))
  1388  	// Make sure a new stochastik will load global variables.
  1389  	tk.Se = nil
  1390  	tk.MustInterDirc("use test")
  1391  	c.Assert(variable.GetMaxDeltaSchemaCount(), Equals, int64(100))
  1392  	tk.MustInterDirc(fmt.Sprintf("set @@global.milevadb_max_delta_schema_count= %v", uint64(math.MaxInt64)))
  1393  	tk.MustQuery("show warnings;").Check(testkit.Events(fmt.Sprintf("Warning 1292 Truncated incorrect milevadb_max_delta_schema_count value: '%d'", uint64(math.MaxInt64))))
  1394  	tk.Se = nil
  1395  	tk.MustInterDirc("use test")
  1396  	c.Assert(variable.GetMaxDeltaSchemaCount(), Equals, int64(16384))
  1397  	_, err := tk.InterDirc("set @@global.milevadb_max_delta_schema_count= invalid_val")
  1398  	c.Assert(terror.ErrorEqual(err, variable.ErrWrongTypeForVar), IsTrue, Commentf("err %v", err))
  1399  
  1400  	tk.MustInterDirc("set @@global.milevadb_max_delta_schema_count= 2048")
  1401  	tk.Se = nil
  1402  	tk.MustInterDirc("use test")
  1403  	c.Assert(variable.GetMaxDeltaSchemaCount(), Equals, int64(2048))
  1404  	tk.MustQuery("select @@global.milevadb_max_delta_schema_count").Check(testkit.Events("2048"))
  1405  }
  1406  
  1407  func (s *seqTestSuite) TestOOMPanicInHashJoinWhenFetchBuildEvents(c *C) {
  1408  	fpName := "github.com/whtcorpsinc/milevadb/interlock/errorFetchBuildSideEventsMockOOMPanic"
  1409  	c.Assert(failpoint.Enable(fpName, `panic("ERROR 1105 (HY000): Out Of Memory Quota![conn_id=1]")`), IsNil)
  1410  	defer func() {
  1411  		c.Assert(failpoint.Disable(fpName), IsNil)
  1412  	}()
  1413  	tk := testkit.NewTestKit(c, s.causetstore)
  1414  	tk.MustInterDirc("use test")
  1415  	tk.MustInterDirc("drop causet if exists t")
  1416  	tk.MustInterDirc("create causet t(c1 int, c2 int)")
  1417  	tk.MustInterDirc("insert into t values(1,1),(2,2)")
  1418  	err := tk.QueryToErr("select * from t as t2  join t as t1 where t1.c1=t2.c1")
  1419  	c.Assert(err.Error(), Equals, "failpoint panic: ERROR 1105 (HY000): Out Of Memory Quota![conn_id=1]")
  1420  }
  1421  
  1422  func (s *seqTestSuite) TestIssue18744(c *C) {
  1423  	tk := testkit.NewTestKitWithInit(c, s.causetstore)
  1424  	tk.MustInterDirc(`use test;`)
  1425  	tk.MustInterDirc(`drop causet if exists t, t1;`)
  1426  	tk.MustInterDirc(`CREATE TABLE t (
  1427    id int(11) NOT NULL,
  1428    a bigint(20) DEFAULT NULL,
  1429    b char(20) DEFAULT NULL,
  1430    c datetime DEFAULT NULL,
  1431    d double DEFAULT NULL,
  1432    e json DEFAULT NULL,
  1433    f decimal(40,6) DEFAULT NULL,
  1434    PRIMARY KEY (id),
  1435    KEY a (a),
  1436    KEY b (b),
  1437    KEY c (c),
  1438    KEY d (d),
  1439    KEY f (f)
  1440  ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;`)
  1441  	tk.MustInterDirc(`CREATE TABLE t1 (
  1442    id int(11) NOT NULL,
  1443    a bigint(20) DEFAULT NULL,
  1444    b char(20) DEFAULT NULL,
  1445    c datetime DEFAULT NULL,
  1446    d double DEFAULT NULL,
  1447    e json DEFAULT NULL,
  1448    f decimal(40,6) DEFAULT NULL,
  1449    PRIMARY KEY (id),
  1450    KEY a (a),
  1451    KEY b (b),
  1452    KEY c (c),
  1453    KEY d (d),
  1454    KEY f (f)
  1455  ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;`)
  1456  	tk.MustInterDirc(`insert into t1(id) values(0),(1),(2);`)
  1457  	tk.MustInterDirc(`insert into t values(0, 2010,  "2010-01-01 01:01:00" , "2010-01-01 01:01:00" , 2010 , 2010 , 2010.000000);`)
  1458  	tk.MustInterDirc(`insert into t values(1 , NULL , NULL                , NULL                , NULL , NULL ,        NULL);`)
  1459  	tk.MustInterDirc(`insert into t values(2 , 2012 , "2012-01-01 01:01:00" , "2012-01-01 01:01:00" , 2012 , 2012 , 2012.000000);`)
  1460  	tk.MustInterDirc(`set milevadb_index_lookup_join_concurrency=1`)
  1461  	c.Assert(failpoint.Enable("github.com/whtcorpsinc/milevadb/interlock/testIndexHashJoinOuterWorkerErr", "return"), IsNil)
  1462  	defer func() {
  1463  		c.Assert(failpoint.Disable("github.com/whtcorpsinc/milevadb/interlock/testIndexHashJoinOuterWorkerErr"), IsNil)
  1464  	}()
  1465  	err := tk.QueryToErr(`select /*+ inl_hash_join(t2) */ t1.id, t2.id from t1 join t t2 on t1.a = t2.a order by t1.a ASC limit 1;`)
  1466  	c.Assert(err.Error(), Equals, "mocHoTTexHashJoinOuterWorkerErr")
  1467  }
  1468  
  1469  func (s *seqTestSuite) TestIssue19410(c *C) {
  1470  	tk := testkit.NewTestKit(c, s.causetstore)
  1471  	tk.MustInterDirc("use test")
  1472  	tk.MustInterDirc("drop causet if exists t, t1, t2, t3;")
  1473  	tk.MustInterDirc("create causet t(a int, b enum('A', 'B'));")
  1474  	tk.MustInterDirc("create causet t1(a1 int, b1 enum('B', 'A') NOT NULL, UNIQUE KEY (b1));")
  1475  	tk.MustInterDirc("insert into t values (1, 'A');")
  1476  	tk.MustInterDirc("insert into t1 values (1, 'A');")
  1477  	tk.MustQuery("select /*+ INL_HASH_JOIN(t1) */ * from t join t1 on t.b = t1.b1;").Check(testkit.Events("1 A 1 A"))
  1478  	tk.MustQuery("select /*+ INL_JOIN(t1) */ * from t join t1 on t.b = t1.b1;").Check(testkit.Events("1 A 1 A"))
  1479  
  1480  	tk.MustInterDirc("create causet t2(a1 int, b1 enum('C', 'D') NOT NULL, UNIQUE KEY (b1));")
  1481  	tk.MustInterDirc("insert into t2 values (1, 'C');")
  1482  	tk.MustQuery("select /*+ INL_HASH_JOIN(t2) */ * from t join t2 on t.b = t2.b1;").Check(testkit.Events())
  1483  	tk.MustQuery("select /*+ INL_JOIN(t2) */ * from t join t2 on t.b = t2.b1;").Check(testkit.Events())
  1484  
  1485  	tk.MustInterDirc("create causet t3(a1 int, b1 enum('A', 'B') NOT NULL, UNIQUE KEY (b1));")
  1486  	tk.MustInterDirc("insert into t3 values (1, 'A');")
  1487  	tk.MustQuery("select /*+ INL_HASH_JOIN(t3) */ * from t join t3 on t.b = t3.b1;").Check(testkit.Events("1 A 1 A"))
  1488  	tk.MustQuery("select /*+ INL_JOIN(t3) */ * from t join t3 on t.b = t3.b1;").Check(testkit.Events("1 A 1 A"))
  1489  }