github.com/whtcorpsinc/milevadb-prod@v0.0.0-20211104133533-f57f4be3b597/schemareplicant/tables_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 schemareplicant_test
    15  
    16  import (
    17  	"crypto/tls"
    18  	"fmt"
    19  	"math"
    20  	"net"
    21  	"net/http/httptest"
    22  	"os"
    23  	"runtime"
    24  	"strings"
    25  	"time"
    26  
    27  	"github.com/gorilla/mux"
    28  	"github.com/whtcorpsinc/BerolinaSQL/allegrosql"
    29  	"github.com/whtcorpsinc/BerolinaSQL/auth"
    30  	"github.com/whtcorpsinc/BerolinaSQL/perceptron"
    31  	"github.com/whtcorpsinc/BerolinaSQL/terror"
    32  	. "github.com/whtcorpsinc/check"
    33  	"github.com/whtcorpsinc/failpoint"
    34  	"github.com/whtcorpsinc/fn"
    35  	causetembedded "github.com/whtcorpsinc/milevadb/causet/embedded"
    36  	"github.com/whtcorpsinc/milevadb/causetstore/helper"
    37  	"github.com/whtcorpsinc/milevadb/causetstore/mockstore"
    38  	"github.com/whtcorpsinc/milevadb/config"
    39  	"github.com/whtcorpsinc/milevadb/ekv"
    40  	"github.com/whtcorpsinc/milevadb/petri"
    41  	"github.com/whtcorpsinc/milevadb/schemareplicant"
    42  	"github.com/whtcorpsinc/milevadb/server"
    43  	"github.com/whtcorpsinc/milevadb/soliton"
    44  	"github.com/whtcorpsinc/milevadb/soliton/FIDelapi"
    45  	"github.com/whtcorpsinc/milevadb/soliton/ekvcache"
    46  	"github.com/whtcorpsinc/milevadb/soliton/set"
    47  	"github.com/whtcorpsinc/milevadb/soliton/solitonutil"
    48  	"github.com/whtcorpsinc/milevadb/soliton/testkit"
    49  	"github.com/whtcorpsinc/milevadb/soliton/testleak"
    50  	"github.com/whtcorpsinc/milevadb/spacetime/autoid"
    51  	"github.com/whtcorpsinc/milevadb/stochastik"
    52  	"google.golang.org/grpc"
    53  )
    54  
    55  var _ = Suite(&testBlockSuite{&testBlockSuiteBase{}})
    56  var _ = SerialSuites(&testClusterBlockSuite{testBlockSuiteBase: &testBlockSuiteBase{}})
    57  
    58  type testBlockSuite struct {
    59  	*testBlockSuiteBase
    60  }
    61  
    62  type testBlockSuiteBase struct {
    63  	causetstore ekv.CausetStorage
    64  	dom         *petri.Petri
    65  }
    66  
    67  func (s *testBlockSuiteBase) SetUpSuite(c *C) {
    68  	testleak.BeforeTest()
    69  
    70  	var err error
    71  	s.causetstore, err = mockstore.NewMockStore()
    72  	c.Assert(err, IsNil)
    73  	stochastik.DisableStats4Test()
    74  	s.dom, err = stochastik.BootstrapStochastik(s.causetstore)
    75  	c.Assert(err, IsNil)
    76  }
    77  
    78  func (s *testBlockSuiteBase) TearDownSuite(c *C) {
    79  	s.dom.Close()
    80  	s.causetstore.Close()
    81  	testleak.AfterTest(c)()
    82  }
    83  
    84  func (s *testBlockSuiteBase) newTestKitWithRoot(c *C) *testkit.TestKit {
    85  	tk := testkit.NewTestKitWithInit(c, s.causetstore)
    86  	c.Assert(tk.Se.Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil), IsTrue)
    87  	return tk
    88  }
    89  
    90  func (s *testBlockSuiteBase) newTestKitWithCausetCache(c *C) *testkit.TestKit {
    91  	tk := testkit.NewTestKit(c, s.causetstore)
    92  	var err error
    93  	tk.Se, err = stochastik.CreateStochastik4TestWithOpt(s.causetstore, &stochastik.Opt{
    94  		PreparedCausetCache: ekvcache.NewSimpleLRUCache(100, 0.1, math.MaxUint64),
    95  	})
    96  	c.Assert(err, IsNil)
    97  	tk.GetConnectionID()
    98  	c.Assert(tk.Se.Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil), IsTrue)
    99  	return tk
   100  }
   101  
   102  type testClusterBlockSuite struct {
   103  	*testBlockSuiteBase
   104  	rpcserver  *grpc.Server
   105  	httpServer *httptest.Server
   106  	mockAddr   string
   107  	listenAddr string
   108  	startTime  time.Time
   109  }
   110  
   111  func (s *testClusterBlockSuite) SetUpSuite(c *C) {
   112  	s.testBlockSuiteBase.SetUpSuite(c)
   113  	s.rpcserver, s.listenAddr = s.setUpRPCService(c, "127.0.0.1:0")
   114  	s.httpServer, s.mockAddr = s.setUpMockFIDelHTTPServer()
   115  	s.startTime = time.Now()
   116  }
   117  
   118  func (s *testClusterBlockSuite) setUpRPCService(c *C, addr string) (*grpc.Server, string) {
   119  	lis, err := net.Listen("tcp", addr)
   120  	c.Assert(err, IsNil)
   121  	// Fix issue 9836
   122  	sm := &mockStochastikManager{make(map[uint64]*soliton.ProcessInfo, 1)}
   123  	sm.processInfoMap[1] = &soliton.ProcessInfo{
   124  		ID:      1,
   125  		User:    "root",
   126  		Host:    "127.0.0.1",
   127  		Command: allegrosql.ComQuery,
   128  	}
   129  	srv := server.NewRPCServer(config.GetGlobalConfig(), s.dom, sm)
   130  	port := lis.Addr().(*net.TCPAddr).Port
   131  	addr = fmt.Sprintf("127.0.0.1:%d", port)
   132  	go func() {
   133  		err = srv.Serve(lis)
   134  		c.Assert(err, IsNil)
   135  	}()
   136  	config.UFIDelateGlobal(func(conf *config.Config) {
   137  		conf.Status.StatusPort = uint(port)
   138  	})
   139  	return srv, addr
   140  }
   141  
   142  func (s *testClusterBlockSuite) setUpMockFIDelHTTPServer() (*httptest.Server, string) {
   143  	// mock FIDel http server
   144  	router := mux.NewRouter()
   145  	server := httptest.NewServer(router)
   146  	// mock causetstore stats stat
   147  	mockAddr := strings.TrimPrefix(server.URL, "http://")
   148  	router.Handle(FIDelapi.Stores, fn.Wrap(func() (*helper.StoresStat, error) {
   149  		return &helper.StoresStat{
   150  			Count: 1,
   151  			Stores: []helper.StoreStat{
   152  				{
   153  					CausetStore: helper.StoreBaseStat{
   154  						ID:             1,
   155  						Address:        "127.0.0.1:20160",
   156  						State:          0,
   157  						StateName:      "Up",
   158  						Version:        "4.0.0-alpha",
   159  						StatusAddress:  mockAddr,
   160  						GitHash:        "mock-einsteindb-githash",
   161  						StartTimestamp: s.startTime.Unix(),
   162  					},
   163  				},
   164  			},
   165  		}, nil
   166  	}))
   167  	// mock FIDel API
   168  	router.Handle(FIDelapi.ClusterVersion, fn.Wrap(func() (string, error) { return "4.0.0-alpha", nil }))
   169  	router.Handle(FIDelapi.Status, fn.Wrap(func() (interface{}, error) {
   170  		return struct {
   171  			GitHash        string `json:"git_hash"`
   172  			StartTimestamp int64  `json:"start_timestamp"`
   173  		}{
   174  			GitHash:        "mock-fidel-githash",
   175  			StartTimestamp: s.startTime.Unix(),
   176  		}, nil
   177  	}))
   178  	var mockConfig = func() (map[string]interface{}, error) {
   179  		configuration := map[string]interface{}{
   180  			"key1": "value1",
   181  			"key2": map[string]string{
   182  				"nest1": "n-value1",
   183  				"nest2": "n-value2",
   184  			},
   185  			"key3": map[string]interface{}{
   186  				"nest1": "n-value1",
   187  				"nest2": "n-value2",
   188  				"key4": map[string]string{
   189  					"nest3": "n-value4",
   190  					"nest4": "n-value5",
   191  				},
   192  			},
   193  		}
   194  		return configuration, nil
   195  	}
   196  	// fidel config
   197  	router.Handle(FIDelapi.Config, fn.Wrap(mockConfig))
   198  	// MilevaDB/EinsteinDB config
   199  	router.Handle("/config", fn.Wrap(mockConfig))
   200  	return server, mockAddr
   201  }
   202  
   203  func (s *testClusterBlockSuite) TearDownSuite(c *C) {
   204  	if s.rpcserver != nil {
   205  		s.rpcserver.Stop()
   206  		s.rpcserver = nil
   207  	}
   208  	if s.httpServer != nil {
   209  		s.httpServer.Close()
   210  	}
   211  	s.testBlockSuiteBase.TearDownSuite(c)
   212  }
   213  
   214  func (s *testBlockSuite) TestschemaReplicantFieldValue(c *C) {
   215  	tk := testkit.NewTestKit(c, s.causetstore)
   216  	tk.MustInterDirc("use test")
   217  	tk.MustInterDirc("drop causet if exists numschema, timeschema")
   218  	tk.MustInterDirc("create causet numschema(i int(2), f float(4,2), d decimal(4,3))")
   219  	tk.MustInterDirc("create causet timeschema(d date, dt datetime(3), ts timestamp(3), t time(4), y year(4))")
   220  	tk.MustInterDirc("create causet strschema(c char(3), c2 varchar(3), b blob(3), t text(3))")
   221  	tk.MustInterDirc("create causet floatschema(a float, b double(7, 3))")
   222  
   223  	tk.MustQuery("select CHARACTER_MAXIMUM_LENGTH,CHARACTER_OCTET_LENGTH,NUMERIC_PRECISION,NUMERIC_SCALE,DATETIME_PRECISION from information_schema.COLUMNS where block_name='numschema'").
   224  		Check(testkit.Rows("<nil> <nil> 2 0 <nil>", "<nil> <nil> 4 2 <nil>", "<nil> <nil> 4 3 <nil>")) // FIXME: for allegrosql first one will be "<nil> <nil> 10 0 <nil>"
   225  	tk.MustQuery("select CHARACTER_MAXIMUM_LENGTH,CHARACTER_OCTET_LENGTH,NUMERIC_PRECISION,NUMERIC_SCALE,DATETIME_PRECISION from information_schema.COLUMNS where block_name='timeschema'").
   226  		Check(testkit.Rows("<nil> <nil> <nil> <nil> <nil>", "<nil> <nil> <nil> <nil> 3", "<nil> <nil> <nil> <nil> 3", "<nil> <nil> <nil> <nil> 4", "<nil> <nil> <nil> <nil> <nil>"))
   227  	tk.MustQuery("select CHARACTER_MAXIMUM_LENGTH,CHARACTER_OCTET_LENGTH,NUMERIC_PRECISION,NUMERIC_SCALE,DATETIME_PRECISION from information_schema.COLUMNS where block_name='strschema'").
   228  		Check(testkit.Rows("3 3 <nil> <nil> <nil>", "3 3 <nil> <nil> <nil>", "3 3 <nil> <nil> <nil>", "3 3 <nil> <nil> <nil>")) // FIXME: for allegrosql last two will be "255 255 <nil> <nil> <nil>", "255 255 <nil> <nil> <nil>"
   229  	tk.MustQuery("select NUMERIC_SCALE from information_schema.COLUMNS where block_name='floatschema'").
   230  		Check(testkit.Rows("<nil>", "3"))
   231  
   232  	// Test for auto increment ID.
   233  	tk.MustInterDirc("drop causet if exists t")
   234  	tk.MustInterDirc("create causet t (c int auto_increment primary key, d int)")
   235  	tk.MustQuery("select auto_increment from information_schema.blocks where block_name='t'").Check(
   236  		testkit.Rows("1"))
   237  	tk.MustInterDirc("insert into t(c, d) values(1, 1)")
   238  	tk.MustQuery("select auto_increment from information_schema.blocks where block_name='t'").Check(
   239  		testkit.Rows("2"))
   240  
   241  	tk.MustQuery("show create causet t").Check(
   242  		testkit.Rows("" +
   243  			"t CREATE TABLE `t` (\n" +
   244  			"  `c` int(11) NOT NULL AUTO_INCREMENT,\n" +
   245  			"  `d` int(11) DEFAULT NULL,\n" +
   246  			"  PRIMARY KEY (`c`)\n" +
   247  			") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin AUTO_INCREMENT=30002"))
   248  
   249  	// Test auto_increment for causet without auto_increment defCausumn
   250  	tk.MustInterDirc("drop causet if exists t")
   251  	tk.MustInterDirc("create causet t (d int)")
   252  	tk.MustQuery("select auto_increment from information_schema.blocks where block_name='t'").Check(
   253  		testkit.Rows("<nil>"))
   254  
   255  	tk.MustInterDirc("create user xxx")
   256  
   257  	// Test for length of enum and set
   258  	tk.MustInterDirc("drop causet if exists t")
   259  	tk.MustInterDirc("create causet t ( s set('a','bc','def','ghij') default NULL, e1 enum('a', 'ab', 'cdef'), s2 SET('1','2','3','4','1585','ONE','TWO','Y','N','THREE'))")
   260  	tk.MustQuery("select defCausumn_name, character_maximum_length from information_schema.defCausumns where block_schema=Database() and block_name = 't' and defCausumn_name = 's'").Check(
   261  		testkit.Rows("s 13"))
   262  	tk.MustQuery("select defCausumn_name, character_maximum_length from information_schema.defCausumns where block_schema=Database() and block_name = 't' and defCausumn_name = 's2'").Check(
   263  		testkit.Rows("s2 30"))
   264  	tk.MustQuery("select defCausumn_name, character_maximum_length from information_schema.defCausumns where block_schema=Database() and block_name = 't' and defCausumn_name = 'e1'").Check(
   265  		testkit.Rows("e1 4"))
   266  
   267  	tk1 := testkit.NewTestKit(c, s.causetstore)
   268  	tk1.MustInterDirc("use test")
   269  	c.Assert(tk1.Se.Auth(&auth.UserIdentity{
   270  		Username: "xxx",
   271  		Hostname: "127.0.0.1",
   272  	}, nil, nil), IsTrue)
   273  
   274  	tk1.MustQuery("select distinct(block_schema) from information_schema.blocks").Check(testkit.Rows("INFORMATION_SCHEMA"))
   275  
   276  	// Fix issue 9836
   277  	sm := &mockStochastikManager{make(map[uint64]*soliton.ProcessInfo, 1)}
   278  	sm.processInfoMap[1] = &soliton.ProcessInfo{
   279  		ID:      1,
   280  		User:    "root",
   281  		Host:    "127.0.0.1",
   282  		Command: allegrosql.ComQuery,
   283  		StmtCtx: tk.Se.GetStochastikVars().StmtCtx,
   284  	}
   285  	tk.Se.SetStochastikManager(sm)
   286  	tk.MustQuery("SELECT user,host,command FROM information_schema.processlist;").Check(testkit.Rows("root 127.0.0.1 Query"))
   287  
   288  	// Test for all system blocks `TABLE_TYPE` is `SYSTEM VIEW`.
   289  	rows1 := tk.MustQuery("select count(*) from information_schema.blocks where block_schema in ('INFORMATION_SCHEMA','PERFORMANCE_SCHEMA','METRICS_SCHEMA');").Rows()
   290  	rows2 := tk.MustQuery("select count(*) from information_schema.blocks where block_schema in ('INFORMATION_SCHEMA','PERFORMANCE_SCHEMA','METRICS_SCHEMA') and  block_type = 'SYSTEM VIEW';").Rows()
   291  	c.Assert(rows1, DeepEquals, rows2)
   292  	// Test for system causet default value
   293  	tk.MustQuery("show create causet information_schema.PROCESSLIST").Check(
   294  		testkit.Rows("" +
   295  			"PROCESSLIST CREATE TABLE `PROCESSLIST` (\n" +
   296  			"  `ID` bigint(21) unsigned NOT NULL DEFAULT 0,\n" +
   297  			"  `USER` varchar(16) NOT NULL DEFAULT '',\n" +
   298  			"  `HOST` varchar(64) NOT NULL DEFAULT '',\n" +
   299  			"  `EDB` varchar(64) DEFAULT NULL,\n" +
   300  			"  `COMMAND` varchar(16) NOT NULL DEFAULT '',\n" +
   301  			"  `TIME` int(7) NOT NULL DEFAULT 0,\n" +
   302  			"  `STATE` varchar(7) DEFAULT NULL,\n" +
   303  			"  `INFO` longtext DEFAULT NULL,\n" +
   304  			"  `DIGEST` varchar(64) DEFAULT '',\n" +
   305  			"  `MEM` bigint(21) unsigned DEFAULT NULL,\n" +
   306  			"  `TxnStart` varchar(64) NOT NULL DEFAULT ''\n" +
   307  			") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin"))
   308  	tk.MustQuery("show create causet information_schema.cluster_log").Check(
   309  		testkit.Rows("" +
   310  			"CLUSTER_LOG CREATE TABLE `CLUSTER_LOG` (\n" +
   311  			"  `TIME` varchar(32) DEFAULT NULL,\n" +
   312  			"  `TYPE` varchar(64) DEFAULT NULL,\n" +
   313  			"  `INSTANCE` varchar(64) DEFAULT NULL,\n" +
   314  			"  `LEVEL` varchar(8) DEFAULT NULL,\n" +
   315  			"  `MESSAGE` longtext DEFAULT NULL\n" +
   316  			") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin"))
   317  }
   318  
   319  func (s *testBlockSuite) TestCharacterSetDefCauslations(c *C) {
   320  	tk := testkit.NewTestKit(c, s.causetstore)
   321  
   322  	// Test charset/defCauslation in information_schema.COLUMNS causet.
   323  	tk.MustInterDirc("DROP DATABASE IF EXISTS charset_defCauslate_test")
   324  	tk.MustInterDirc("CREATE DATABASE charset_defCauslate_test; USE charset_defCauslate_test")
   325  
   326  	// TODO: Specifying the charset for national char/varchar should not be supported.
   327  	tk.MustInterDirc(`CREATE TABLE charset_defCauslate_defCaus_test(
   328  		c_int int,
   329  		c_float float,
   330  		c_bit bit,
   331  		c_bool bool,
   332  		c_char char(1) charset ascii defCauslate ascii_bin,
   333  		c_nchar national char(1) charset ascii defCauslate ascii_bin,
   334  		c_binary binary,
   335  		c_varchar varchar(1) charset ascii defCauslate ascii_bin,
   336  		c_nvarchar national varchar(1) charset ascii defCauslate ascii_bin,
   337  		c_varbinary varbinary(1),
   338  		c_year year,
   339  		c_date date,
   340  		c_time time,
   341  		c_datetime datetime,
   342  		c_timestamp timestamp,
   343  		c_blob blob,
   344  		c_tinyblob tinyblob,
   345  		c_mediumblob mediumblob,
   346  		c_longblob longblob,
   347  		c_text text charset ascii defCauslate ascii_bin,
   348  		c_tinytext tinytext charset ascii defCauslate ascii_bin,
   349  		c_mediumtext mediumtext charset ascii defCauslate ascii_bin,
   350  		c_longtext longtext charset ascii defCauslate ascii_bin,
   351  		c_json json,
   352  		c_enum enum('1') charset ascii defCauslate ascii_bin,
   353  		c_set set('1') charset ascii defCauslate ascii_bin
   354  	)`)
   355  
   356  	tk.MustQuery(`SELECT defCausumn_name, character_set_name, defCauslation_name
   357  					FROM information_schema.COLUMNS
   358  					WHERE block_schema = "charset_defCauslate_test" AND block_name = "charset_defCauslate_defCaus_test"
   359  					ORDER BY defCausumn_name`,
   360  	).Check(testkit.Rows(
   361  		"c_binary <nil> <nil>",
   362  		"c_bit <nil> <nil>",
   363  		"c_blob <nil> <nil>",
   364  		"c_bool <nil> <nil>",
   365  		"c_char ascii ascii_bin",
   366  		"c_date <nil> <nil>",
   367  		"c_datetime <nil> <nil>",
   368  		"c_enum ascii ascii_bin",
   369  		"c_float <nil> <nil>",
   370  		"c_int <nil> <nil>",
   371  		"c_json <nil> <nil>",
   372  		"c_longblob <nil> <nil>",
   373  		"c_longtext ascii ascii_bin",
   374  		"c_mediumblob <nil> <nil>",
   375  		"c_mediumtext ascii ascii_bin",
   376  		"c_nchar ascii ascii_bin",
   377  		"c_nvarchar ascii ascii_bin",
   378  		"c_set ascii ascii_bin",
   379  		"c_text ascii ascii_bin",
   380  		"c_time <nil> <nil>",
   381  		"c_timestamp <nil> <nil>",
   382  		"c_tinyblob <nil> <nil>",
   383  		"c_tinytext ascii ascii_bin",
   384  		"c_varbinary <nil> <nil>",
   385  		"c_varchar ascii ascii_bin",
   386  		"c_year <nil> <nil>",
   387  	))
   388  	tk.MustInterDirc("DROP DATABASE charset_defCauslate_test")
   389  }
   390  
   391  func (s *testBlockSuite) TestCurrentTimestampAsDefault(c *C) {
   392  	tk := testkit.NewTestKit(c, s.causetstore)
   393  
   394  	tk.MustInterDirc("DROP DATABASE IF EXISTS default_time_test")
   395  	tk.MustInterDirc("CREATE DATABASE default_time_test; USE default_time_test")
   396  
   397  	tk.MustInterDirc(`CREATE TABLE default_time_block(
   398  					c_datetime datetime,
   399  					c_datetime_default datetime default current_timestamp,
   400  					c_datetime_default_2 datetime(2) default current_timestamp(2),
   401  					c_timestamp timestamp,
   402  					c_timestamp_default timestamp default current_timestamp,
   403  					c_timestamp_default_3 timestamp(3) default current_timestamp(3),
   404  					c_varchar_default varchar(20) default "current_timestamp",
   405  					c_varchar_default_3 varchar(20) default "current_timestamp(3)",
   406  					c_varchar_default_on_uFIDelate datetime default current_timestamp on uFIDelate current_timestamp,
   407  					c_varchar_default_on_uFIDelate_fsp datetime(3) default current_timestamp(3) on uFIDelate current_timestamp(3),
   408  					c_varchar_default_with_case varchar(20) default "cUrrent_tImestamp"
   409  				);`)
   410  
   411  	tk.MustQuery(`SELECT defCausumn_name, defCausumn_default, extra
   412  					FROM information_schema.COLUMNS
   413  					WHERE block_schema = "default_time_test" AND block_name = "default_time_block"
   414  					ORDER BY defCausumn_name`,
   415  	).Check(testkit.Rows(
   416  		"c_datetime <nil> ",
   417  		"c_datetime_default CURRENT_TIMESTAMP ",
   418  		"c_datetime_default_2 CURRENT_TIMESTAMP(2) ",
   419  		"c_timestamp <nil> ",
   420  		"c_timestamp_default CURRENT_TIMESTAMP ",
   421  		"c_timestamp_default_3 CURRENT_TIMESTAMP(3) ",
   422  		"c_varchar_default current_timestamp ",
   423  		"c_varchar_default_3 current_timestamp(3) ",
   424  		"c_varchar_default_on_uFIDelate CURRENT_TIMESTAMP DEFAULT_GENERATED on uFIDelate CURRENT_TIMESTAMP",
   425  		"c_varchar_default_on_uFIDelate_fsp CURRENT_TIMESTAMP(3) DEFAULT_GENERATED on uFIDelate CURRENT_TIMESTAMP(3)",
   426  		"c_varchar_default_with_case cUrrent_tImestamp ",
   427  	))
   428  	tk.MustInterDirc("DROP DATABASE default_time_test")
   429  }
   430  
   431  type mockStochastikManager struct {
   432  	processInfoMap map[uint64]*soliton.ProcessInfo
   433  }
   434  
   435  func (sm *mockStochastikManager) ShowProcessList() map[uint64]*soliton.ProcessInfo {
   436  	return sm.processInfoMap
   437  }
   438  
   439  func (sm *mockStochastikManager) GetProcessInfo(id uint64) (*soliton.ProcessInfo, bool) {
   440  	rs, ok := sm.processInfoMap[id]
   441  	return rs, ok
   442  }
   443  
   444  func (sm *mockStochastikManager) Kill(connectionID uint64, query bool) {}
   445  
   446  func (sm *mockStochastikManager) UFIDelateTLSConfig(cfg *tls.Config) {}
   447  
   448  func (s *testBlockSuite) TestSomeBlocks(c *C) {
   449  	se, err := stochastik.CreateStochastik4Test(s.causetstore)
   450  	c.Assert(err, IsNil)
   451  	tk := testkit.NewTestKit(c, s.causetstore)
   452  	tk.Se = se
   453  	sm := &mockStochastikManager{make(map[uint64]*soliton.ProcessInfo, 2)}
   454  	sm.processInfoMap[1] = &soliton.ProcessInfo{
   455  		ID:      1,
   456  		User:    "user-1",
   457  		Host:    "localhost",
   458  		EDB:     "information_schema",
   459  		Command: byte(1),
   460  		Digest:  "abc1",
   461  		State:   1,
   462  		Info:    "do something",
   463  		StmtCtx: tk.Se.GetStochastikVars().StmtCtx,
   464  	}
   465  	sm.processInfoMap[2] = &soliton.ProcessInfo{
   466  		ID:      2,
   467  		User:    "user-2",
   468  		Host:    "localhost",
   469  		EDB:     "test",
   470  		Command: byte(2),
   471  		Digest:  "abc2",
   472  		State:   2,
   473  		Info:    strings.Repeat("x", 101),
   474  		StmtCtx: tk.Se.GetStochastikVars().StmtCtx,
   475  	}
   476  	tk.Se.SetStochastikManager(sm)
   477  	tk.MustQuery("select * from information_schema.PROCESSLIST order by ID;").Sort().Check(
   478  		testkit.Rows(
   479  			fmt.Sprintf("1 user-1 localhost information_schema Quit 9223372036 %s %s abc1 0 ", "in transaction", "do something"),
   480  			fmt.Sprintf("2 user-2 localhost test Init EDB 9223372036 %s %s abc2 0 ", "autocommit", strings.Repeat("x", 101)),
   481  		))
   482  	tk.MustQuery("SHOW PROCESSLIST;").Sort().Check(
   483  		testkit.Rows(
   484  			fmt.Sprintf("1 user-1 localhost information_schema Quit 9223372036 %s %s", "in transaction", "do something"),
   485  			fmt.Sprintf("2 user-2 localhost test Init EDB 9223372036 %s %s", "autocommit", strings.Repeat("x", 100)),
   486  		))
   487  	tk.MustQuery("SHOW FULL PROCESSLIST;").Sort().Check(
   488  		testkit.Rows(
   489  			fmt.Sprintf("1 user-1 localhost information_schema Quit 9223372036 %s %s", "in transaction", "do something"),
   490  			fmt.Sprintf("2 user-2 localhost test Init EDB 9223372036 %s %s", "autocommit", strings.Repeat("x", 101)),
   491  		))
   492  
   493  	sm = &mockStochastikManager{make(map[uint64]*soliton.ProcessInfo, 2)}
   494  	sm.processInfoMap[1] = &soliton.ProcessInfo{
   495  		ID:      1,
   496  		User:    "user-1",
   497  		Host:    "localhost",
   498  		EDB:     "information_schema",
   499  		Command: byte(1),
   500  		Digest:  "abc1",
   501  		State:   1,
   502  		StmtCtx: tk.Se.GetStochastikVars().StmtCtx,
   503  	}
   504  	sm.processInfoMap[2] = &soliton.ProcessInfo{
   505  		ID:            2,
   506  		User:          "user-2",
   507  		Host:          "localhost",
   508  		Command:       byte(2),
   509  		Digest:        "abc2",
   510  		State:         2,
   511  		Info:          strings.Repeat("x", 101),
   512  		StmtCtx:       tk.Se.GetStochastikVars().StmtCtx,
   513  		CurTxnStartTS: 410090409861578752,
   514  	}
   515  	tk.Se.SetStochastikManager(sm)
   516  	tk.Se.GetStochastikVars().TimeZone = time.UTC
   517  	tk.MustQuery("select * from information_schema.PROCESSLIST order by ID;").Check(
   518  		testkit.Rows(
   519  			fmt.Sprintf("1 user-1 localhost information_schema Quit 9223372036 %s %s abc1 0 ", "in transaction", "<nil>"),
   520  			fmt.Sprintf("2 user-2 localhost <nil> Init EDB 9223372036 %s %s abc2 0 07-29 03:26:05.158(410090409861578752)", "autocommit", strings.Repeat("x", 101)),
   521  		))
   522  	tk.MustQuery("SHOW PROCESSLIST;").Sort().Check(
   523  		testkit.Rows(
   524  			fmt.Sprintf("1 user-1 localhost information_schema Quit 9223372036 %s %s", "in transaction", "<nil>"),
   525  			fmt.Sprintf("2 user-2 localhost <nil> Init EDB 9223372036 %s %s", "autocommit", strings.Repeat("x", 100)),
   526  		))
   527  	tk.MustQuery("SHOW FULL PROCESSLIST;").Sort().Check(
   528  		testkit.Rows(
   529  			fmt.Sprintf("1 user-1 localhost information_schema Quit 9223372036 %s %s", "in transaction", "<nil>"),
   530  			fmt.Sprintf("2 user-2 localhost <nil> Init EDB 9223372036 %s %s", "autocommit", strings.Repeat("x", 101)),
   531  		))
   532  	tk.MustQuery("select * from information_schema.PROCESSLIST where EDB is null;").Check(
   533  		testkit.Rows(
   534  			fmt.Sprintf("2 user-2 localhost <nil> Init EDB 9223372036 %s %s abc2 0 07-29 03:26:05.158(410090409861578752)", "autocommit", strings.Repeat("x", 101)),
   535  		))
   536  	tk.MustQuery("select * from information_schema.PROCESSLIST where Info is null;").Check(
   537  		testkit.Rows(
   538  			fmt.Sprintf("1 user-1 localhost information_schema Quit 9223372036 %s %s abc1 0 ", "in transaction", "<nil>"),
   539  		))
   540  }
   541  
   542  func prepareSlowLogfile(c *C, slowLogFileName string) {
   543  	f, err := os.OpenFile(slowLogFileName, os.O_CREATE|os.O_WRONLY, 0644)
   544  	c.Assert(err, IsNil)
   545  	_, err = f.Write([]byte(`# Time: 2020-02-12T19:33:56.571953+08:00
   546  # Txn_start_ts: 406315658548871171
   547  # User@Host: root[root] @ localhost [127.0.0.1]
   548  # Conn_ID: 6
   549  # InterDirc_retry_time: 0.12 InterDirc_retry_count: 57
   550  # Query_time: 4.895492
   551  # Parse_time: 0.4
   552  # Compile_time: 0.2
   553  # Rewrite_time: 0.000000003 Preproc_subqueries: 2 Preproc_subqueries_time: 0.000000002
   554  # Optimize_time: 0.00000001
   555  # Wait_TS: 0.000000003
   556  # LockKeys_time: 1.71 Request_count: 1 Prewrite_time: 0.19 Wait_prewrite_binlog_time: 0.21 Commit_time: 0.01 Commit_backoff_time: 0.18 Backoff_types: [txnLock] Resolve_lock_time: 0.03 Write_keys: 15 Write_size: 480 Prewrite_region: 1 Txn_retry: 8
   557  # Cop_time: 0.3824278 Process_time: 0.161 Request_count: 1 Total_keys: 100001 Process_keys: 100000
   558  # Wait_time: 0.101
   559  # Backoff_time: 0.092
   560  # EDB: test
   561  # Is_internal: false
   562  # Digest: 42a1c8aae6f133e934d4bf0147491709a8812ea05ff8819ec522780fe657b772
   563  # Stats: t1:1,t2:2
   564  # Cop_proc_avg: 0.1 Cop_proc_p90: 0.2 Cop_proc_max: 0.03 Cop_proc_addr: 127.0.0.1:20160
   565  # Cop_wait_avg: 0.05 Cop_wait_p90: 0.6 Cop_wait_max: 0.8 Cop_wait_addr: 0.0.0.0:20160
   566  # Mem_max: 70724
   567  # Disk_max: 65536
   568  # Causet_from_cache: true
   569  # Succ: true
   570  # Causet: abcd
   571  # Causet_digest: 60e9378c746d9a2be1c791047e008967cf252eb6de9167ad3aa6098fa2d523f4
   572  # Prev_stmt: uFIDelate t set i = 2;
   573  select * from t_slim;`))
   574  	c.Assert(f.Close(), IsNil)
   575  	c.Assert(err, IsNil)
   576  }
   577  
   578  func (s *testBlockSuite) TestBlockRowIDShardingInfo(c *C) {
   579  	tk := testkit.NewTestKit(c, s.causetstore)
   580  	tk.MustInterDirc("DROP DATABASE IF EXISTS `sharding_info_test_db`")
   581  	tk.MustInterDirc("CREATE DATABASE `sharding_info_test_db`")
   582  
   583  	assertShardingInfo := func(blockName string, expectInfo interface{}) {
   584  		queryALLEGROSQL := fmt.Sprintf("select milevadb_row_id_sharding_info from information_schema.blocks where block_schema = 'sharding_info_test_db' and block_name = '%s'", blockName)
   585  		info := tk.MustQuery(queryALLEGROSQL).Rows()[0][0]
   586  		if expectInfo == nil {
   587  			c.Assert(info, Equals, "<nil>")
   588  		} else {
   589  			c.Assert(info, Equals, expectInfo)
   590  		}
   591  	}
   592  	tk.MustInterDirc("CREATE TABLE `sharding_info_test_db`.`t1` (a int)")
   593  	assertShardingInfo("t1", "NOT_SHARDED")
   594  
   595  	tk.MustInterDirc("CREATE TABLE `sharding_info_test_db`.`t2` (a int key)")
   596  	assertShardingInfo("t2", "NOT_SHARDED(PK_IS_HANDLE)")
   597  
   598  	tk.MustInterDirc("CREATE TABLE `sharding_info_test_db`.`t3` (a int) SHARD_ROW_ID_BITS=4")
   599  	assertShardingInfo("t3", "SHARD_BITS=4")
   600  
   601  	tk.MustInterDirc("CREATE VIEW `sharding_info_test_db`.`tv` AS select 1")
   602  	assertShardingInfo("tv", nil)
   603  
   604  	testFunc := func(dbName string, expectInfo interface{}) {
   605  		dbInfo := perceptron.DBInfo{Name: perceptron.NewCIStr(dbName)}
   606  		blockInfo := perceptron.BlockInfo{}
   607  
   608  		info := schemareplicant.GetShardingInfo(&dbInfo, &blockInfo)
   609  		c.Assert(info, Equals, expectInfo)
   610  	}
   611  
   612  	testFunc("information_schema", nil)
   613  	testFunc("allegrosql", nil)
   614  	testFunc("performance_schema", nil)
   615  	testFunc("uucc", "NOT_SHARDED")
   616  
   617  	solitonutil.ConfigTestUtils.SetupAutoRandomTestConfig()
   618  	defer solitonutil.ConfigTestUtils.RestoreAutoRandomTestConfig()
   619  
   620  	tk.MustInterDirc("CREATE TABLE `sharding_info_test_db`.`t4` (a bigint key auto_random)")
   621  	assertShardingInfo("t4", "PK_AUTO_RANDOM_BITS=5")
   622  
   623  	tk.MustInterDirc("CREATE TABLE `sharding_info_test_db`.`t5` (a bigint key auto_random(1))")
   624  	assertShardingInfo("t5", "PK_AUTO_RANDOM_BITS=1")
   625  
   626  	tk.MustInterDirc("DROP DATABASE `sharding_info_test_db`")
   627  }
   628  
   629  func (s *testBlockSuite) TestSlowQuery(c *C) {
   630  	tk := testkit.NewTestKit(c, s.causetstore)
   631  	// Prepare slow log file.
   632  	slowLogFileName := "milevadb_slow.log"
   633  	prepareSlowLogfile(c, slowLogFileName)
   634  	defer os.Remove(slowLogFileName)
   635  
   636  	tk.MustInterDirc(fmt.Sprintf("set @@milevadb_slow_query_file='%v'", slowLogFileName))
   637  	tk.MustInterDirc("set time_zone = '+08:00';")
   638  	re := tk.MustQuery("select * from information_schema.slow_query")
   639  	re.Check(solitonutil.RowsWithSep("|",
   640  		"2020-02-12 19:33:56.571953|406315658548871171|root|localhost|6|57|0.12|4.895492|0.4|0.2|0.000000003|2|0.000000002|0.00000001|0.000000003|0.19|0.21|0.01|0|0.18|[txnLock]|0.03|0|15|480|1|8|0.3824278|0.161|0.101|0.092|1.71|1|100001|100000|test||0|42a1c8aae6f133e934d4bf0147491709a8812ea05ff8819ec522780fe657b772|t1:1,t2:2|0.1|0.2|0.03|127.0.0.1:20160|0.05|0.6|0.8|0.0.0.0:20160|70724|65536|1|1|abcd|60e9378c746d9a2be1c791047e008967cf252eb6de9167ad3aa6098fa2d523f4|uFIDelate t set i = 2;|select * from t_slim;"))
   641  	tk.MustInterDirc("set time_zone = '+00:00';")
   642  	re = tk.MustQuery("select * from information_schema.slow_query")
   643  	re.Check(solitonutil.RowsWithSep("|", "2020-02-12 11:33:56.571953|406315658548871171|root|localhost|6|57|0.12|4.895492|0.4|0.2|0.000000003|2|0.000000002|0.00000001|0.000000003|0.19|0.21|0.01|0|0.18|[txnLock]|0.03|0|15|480|1|8|0.3824278|0.161|0.101|0.092|1.71|1|100001|100000|test||0|42a1c8aae6f133e934d4bf0147491709a8812ea05ff8819ec522780fe657b772|t1:1,t2:2|0.1|0.2|0.03|127.0.0.1:20160|0.05|0.6|0.8|0.0.0.0:20160|70724|65536|1|1|abcd|60e9378c746d9a2be1c791047e008967cf252eb6de9167ad3aa6098fa2d523f4|uFIDelate t set i = 2;|select * from t_slim;"))
   644  
   645  	// Test for long query.
   646  	f, err := os.OpenFile(slowLogFileName, os.O_CREATE|os.O_WRONLY, 0644)
   647  	c.Assert(err, IsNil)
   648  	defer f.Close()
   649  	_, err = f.Write([]byte(`
   650  # Time: 2020-02-13T19:33:56.571953+08:00
   651  `))
   652  	c.Assert(err, IsNil)
   653  	allegrosql := "select * from "
   654  	for len(allegrosql) < 5000 {
   655  		allegrosql += "abcdefghijklmnopqrstuvwxyz_1234567890_qwertyuiopasdfghjklzxcvbnm"
   656  	}
   657  	allegrosql += ";"
   658  	_, err = f.Write([]byte(allegrosql))
   659  	c.Assert(err, IsNil)
   660  	c.Assert(f.Close(), IsNil)
   661  	re = tk.MustQuery("select query from information_schema.slow_query order by time desc limit 1")
   662  	rows := re.Rows()
   663  	c.Assert(rows[0][0], Equals, allegrosql)
   664  }
   665  
   666  func (s *testBlockSuite) TestDeferredCausetStatistics(c *C) {
   667  	tk := testkit.NewTestKit(c, s.causetstore)
   668  	tk.MustQuery("select * from information_schema.defCausumn_statistics").Check(testkit.Rows())
   669  }
   670  
   671  func (s *testBlockSuite) TestReloadDroFIDelatabase(c *C) {
   672  	tk := testkit.NewTestKit(c, s.causetstore)
   673  	tk.MustInterDirc("create database test_dbs")
   674  	tk.MustInterDirc("use test_dbs")
   675  	tk.MustInterDirc("create causet t1 (a int)")
   676  	tk.MustInterDirc("create causet t2 (a int)")
   677  	tk.MustInterDirc("create causet t3 (a int)")
   678  	is := petri.GetPetri(tk.Se).SchemaReplicant()
   679  	t2, err := is.BlockByName(perceptron.NewCIStr("test_dbs"), perceptron.NewCIStr("t2"))
   680  	c.Assert(err, IsNil)
   681  	tk.MustInterDirc("drop database test_dbs")
   682  	is = petri.GetPetri(tk.Se).SchemaReplicant()
   683  	_, err = is.BlockByName(perceptron.NewCIStr("test_dbs"), perceptron.NewCIStr("t2"))
   684  	c.Assert(terror.ErrorEqual(schemareplicant.ErrBlockNotExists, err), IsTrue)
   685  	_, ok := is.BlockByID(t2.Meta().ID)
   686  	c.Assert(ok, IsFalse)
   687  }
   688  
   689  func (s *testClusterBlockSuite) TestForClusterServerInfo(c *C) {
   690  	tk := testkit.NewTestKit(c, s.causetstore)
   691  	instances := []string{
   692  		strings.Join([]string{"milevadb", s.listenAddr, s.listenAddr, "mock-version,mock-githash"}, ","),
   693  		strings.Join([]string{"fidel", s.listenAddr, s.listenAddr, "mock-version,mock-githash"}, ","),
   694  		strings.Join([]string{"einsteindb", s.listenAddr, s.listenAddr, "mock-version,mock-githash"}, ","),
   695  	}
   696  
   697  	fpExpr := `return("` + strings.Join(instances, ";") + `")`
   698  	fpName := "github.com/whtcorpsinc/milevadb/schemareplicant/mockClusterInfo"
   699  	c.Assert(failpoint.Enable(fpName, fpExpr), IsNil)
   700  	defer func() { c.Assert(failpoint.Disable(fpName), IsNil) }()
   701  
   702  	cases := []struct {
   703  		allegrosql string
   704  		types      set.StringSet
   705  		addrs      set.StringSet
   706  		names      set.StringSet
   707  		skipOnOS   string
   708  	}{
   709  		{
   710  			allegrosql: "select * from information_schema.CLUSTER_LOAD;",
   711  			types:      set.NewStringSet("milevadb", "einsteindb", "fidel"),
   712  			addrs:      set.NewStringSet(s.listenAddr),
   713  			names:      set.NewStringSet("cpu", "memory", "net"),
   714  		},
   715  		{
   716  			allegrosql: "select * from information_schema.CLUSTER_HARDWARE;",
   717  			types:      set.NewStringSet("milevadb", "einsteindb", "fidel"),
   718  			addrs:      set.NewStringSet(s.listenAddr),
   719  			names:      set.NewStringSet("cpu", "memory", "net", "disk"),
   720  			// The sysutil package will filter out all disk don't have /dev prefix.
   721  			skipOnOS: "windows",
   722  		},
   723  		{
   724  			allegrosql: "select * from information_schema.CLUSTER_SYSTEMINFO;",
   725  			types:      set.NewStringSet("milevadb", "einsteindb", "fidel"),
   726  			addrs:      set.NewStringSet(s.listenAddr),
   727  			names:      set.NewStringSet("system"),
   728  			// This test get empty result and fails on the windows platform.
   729  			// Because the underlying implementation use `sysctl` command to get the result
   730  			// and there is no such command on windows.
   731  			// https://github.com/whtcorpsinc/sysutil/blob/2bfa6dc40bcd4c103bf684fba528ae4279c7ec9f/system_info.go#L50
   732  			skipOnOS: "windows",
   733  		},
   734  	}
   735  
   736  	for _, cas := range cases {
   737  		if cas.skipOnOS == runtime.GOOS {
   738  			continue
   739  		}
   740  
   741  		result := tk.MustQuery(cas.allegrosql)
   742  		rows := result.Rows()
   743  		c.Assert(len(rows), Greater, 0)
   744  
   745  		gotTypes := set.StringSet{}
   746  		gotAddrs := set.StringSet{}
   747  		gotNames := set.StringSet{}
   748  
   749  		for _, event := range rows {
   750  			gotTypes.Insert(event[0].(string))
   751  			gotAddrs.Insert(event[1].(string))
   752  			gotNames.Insert(event[2].(string))
   753  		}
   754  
   755  		c.Assert(gotTypes, DeepEquals, cas.types, Commentf("allegrosql: %s", cas.allegrosql))
   756  		c.Assert(gotAddrs, DeepEquals, cas.addrs, Commentf("allegrosql: %s", cas.allegrosql))
   757  		c.Assert(gotNames, DeepEquals, cas.names, Commentf("allegrosql: %s", cas.allegrosql))
   758  	}
   759  }
   760  
   761  func (s *testBlockSuite) TestSystemSchemaID(c *C) {
   762  	uniqueIDMap := make(map[int64]string)
   763  	s.checkSystemSchemaBlockID(c, "information_schema", autoid.InformationSchemaDBID, 1, 10000, uniqueIDMap)
   764  	s.checkSystemSchemaBlockID(c, "performance_schema", autoid.PerformanceSchemaDBID, 10000, 20000, uniqueIDMap)
   765  	s.checkSystemSchemaBlockID(c, "metrics_schema", autoid.MetricSchemaDBID, 20000, 30000, uniqueIDMap)
   766  }
   767  
   768  func (s *testBlockSuite) checkSystemSchemaBlockID(c *C, dbName string, dbID, start, end int64, uniqueIDMap map[int64]string) {
   769  	is := s.dom.SchemaReplicant()
   770  	c.Assert(is, NotNil)
   771  	EDB, ok := is.SchemaByName(perceptron.NewCIStr(dbName))
   772  	c.Assert(ok, IsTrue)
   773  	c.Assert(EDB.ID, Equals, dbID)
   774  	// Test for information_schema causet id.
   775  	blocks := is.SchemaBlocks(perceptron.NewCIStr(dbName))
   776  	c.Assert(len(blocks), Greater, 0)
   777  	for _, tbl := range blocks {
   778  		tid := tbl.Meta().ID
   779  		comment := Commentf("causet name is %v", tbl.Meta().Name)
   780  		c.Assert(tid&autoid.SystemSchemaIDFlag, Greater, int64(0), comment)
   781  		c.Assert(tid&^autoid.SystemSchemaIDFlag, Greater, start, comment)
   782  		c.Assert(tid&^autoid.SystemSchemaIDFlag, Less, end, comment)
   783  		name, ok := uniqueIDMap[tid]
   784  		c.Assert(ok, IsFalse, Commentf("schemaReplicant id of %v is duplicate with %v, both is %v", name, tbl.Meta().Name, tid))
   785  		uniqueIDMap[tid] = tbl.Meta().Name.O
   786  	}
   787  }
   788  
   789  func (s *testClusterBlockSuite) TestSelectClusterBlock(c *C) {
   790  	tk := s.newTestKitWithRoot(c)
   791  	slowLogFileName := "milevadb-slow.log"
   792  	prepareSlowLogfile(c, slowLogFileName)
   793  	defer os.Remove(slowLogFileName)
   794  	for i := 0; i < 2; i++ {
   795  		tk.MustInterDirc("use information_schema")
   796  		tk.MustInterDirc(fmt.Sprintf("set @@milevadb_enable_streaming=%d", i))
   797  		tk.MustInterDirc("set @@global.milevadb_enable_stmt_summary=1")
   798  		tk.MustQuery("select count(*) from `CLUSTER_SLOW_QUERY`").Check(testkit.Rows("1"))
   799  		tk.MustQuery("select time from `CLUSTER_SLOW_QUERY` where time='2020-02-12 19:33:56.571953'").Check(solitonutil.RowsWithSep("|", "2020-02-12 19:33:56.571953"))
   800  		tk.MustQuery("select count(*) from `CLUSTER_PROCESSLIST`").Check(testkit.Rows("1"))
   801  		tk.MustQuery("select * from `CLUSTER_PROCESSLIST`").Check(testkit.Rows(fmt.Sprintf(":10080 1 root 127.0.0.1 <nil> Query 9223372036 %s <nil>  0 ", "")))
   802  		tk.MustQuery("select query_time, conn_id from `CLUSTER_SLOW_QUERY` order by time limit 1").Check(testkit.Rows("4.895492 6"))
   803  		tk.MustQuery("select count(*) from `CLUSTER_SLOW_QUERY` group by digest").Check(testkit.Rows("1"))
   804  		tk.MustQuery("select digest, count(*) from `CLUSTER_SLOW_QUERY` group by digest").Check(testkit.Rows("42a1c8aae6f133e934d4bf0147491709a8812ea05ff8819ec522780fe657b772 1"))
   805  		tk.MustQuery("select count(*) from `CLUSTER_SLOW_QUERY` where time > now() group by digest").Check(testkit.Rows())
   806  		re := tk.MustQuery("select * from `CLUSTER_memexs_summary`")
   807  		c.Assert(re, NotNil)
   808  		c.Assert(len(re.Rows()) > 0, IsTrue)
   809  		// Test for MilevaDB issue 14915.
   810  		re = tk.MustQuery("select sum(exec_count*avg_mem) from cluster_memexs_summary_history group by schema_name,digest,digest_text;")
   811  		c.Assert(re, NotNil)
   812  		c.Assert(len(re.Rows()) > 0, IsTrue)
   813  		tk.MustQuery("select * from `CLUSTER_memexs_summary_history`")
   814  		c.Assert(re, NotNil)
   815  		c.Assert(len(re.Rows()) > 0, IsTrue)
   816  		tk.MustInterDirc("set @@global.milevadb_enable_stmt_summary=0")
   817  		re = tk.MustQuery("select * from `CLUSTER_memexs_summary`")
   818  		c.Assert(re, NotNil)
   819  		c.Assert(len(re.Rows()) == 0, IsTrue)
   820  		tk.MustQuery("select * from `CLUSTER_memexs_summary_history`")
   821  		c.Assert(re, NotNil)
   822  		c.Assert(len(re.Rows()) == 0, IsTrue)
   823  	}
   824  }
   825  
   826  func (s *testClusterBlockSuite) TestSelectClusterBlockPrivelege(c *C) {
   827  	tk := testkit.NewTestKit(c, s.causetstore)
   828  	slowLogFileName := "milevadb-slow.log"
   829  	f, err := os.OpenFile(slowLogFileName, os.O_CREATE|os.O_WRONLY, 0644)
   830  	c.Assert(err, IsNil)
   831  	_, err = f.Write([]byte(
   832  		`# Time: 2020-02-12T19:33:57.571953+08:00
   833  # User@Host: user2 [user2] @ 127.0.0.1 [127.0.0.1]
   834  select * from t2;
   835  # Time: 2020-02-12T19:33:56.571953+08:00
   836  # User@Host: user1 [user1] @ 127.0.0.1 [127.0.0.1]
   837  select * from t1;
   838  # Time: 2020-02-12T19:33:58.571953+08:00
   839  # User@Host: user2 [user2] @ 127.0.0.1 [127.0.0.1]
   840  select * from t3;
   841  # Time: 2020-02-12T19:33:59.571953+08:00
   842  select * from t3;
   843  `))
   844  	c.Assert(f.Close(), IsNil)
   845  	c.Assert(err, IsNil)
   846  	defer os.Remove(slowLogFileName)
   847  	tk.MustInterDirc("use information_schema")
   848  	tk.MustQuery("select count(*) from `CLUSTER_SLOW_QUERY`").Check(testkit.Rows("4"))
   849  	tk.MustQuery("select count(*) from `SLOW_QUERY`").Check(testkit.Rows("4"))
   850  	tk.MustQuery("select count(*) from `CLUSTER_PROCESSLIST`").Check(testkit.Rows("1"))
   851  	tk.MustQuery("select * from `CLUSTER_PROCESSLIST`").Check(testkit.Rows(fmt.Sprintf(":10080 1 root 127.0.0.1 <nil> Query 9223372036 %s <nil>  0 ", "")))
   852  	tk.MustInterDirc("create user user1")
   853  	tk.MustInterDirc("create user user2")
   854  	user1 := testkit.NewTestKit(c, s.causetstore)
   855  	user1.MustInterDirc("use information_schema")
   856  	c.Assert(user1.Se.Auth(&auth.UserIdentity{
   857  		Username: "user1",
   858  		Hostname: "127.0.0.1",
   859  	}, nil, nil), IsTrue)
   860  	user1.MustQuery("select count(*) from `CLUSTER_SLOW_QUERY`").Check(testkit.Rows("1"))
   861  	user1.MustQuery("select count(*) from `SLOW_QUERY`").Check(testkit.Rows("1"))
   862  	user1.MustQuery("select user,query from `CLUSTER_SLOW_QUERY`").Check(testkit.Rows("user1 select * from t1;"))
   863  
   864  	user2 := testkit.NewTestKit(c, s.causetstore)
   865  	user2.MustInterDirc("use information_schema")
   866  	c.Assert(user2.Se.Auth(&auth.UserIdentity{
   867  		Username: "user2",
   868  		Hostname: "127.0.0.1",
   869  	}, nil, nil), IsTrue)
   870  	user2.MustQuery("select count(*) from `CLUSTER_SLOW_QUERY`").Check(testkit.Rows("2"))
   871  	user2.MustQuery("select user,query from `CLUSTER_SLOW_QUERY` order by query").Check(testkit.Rows("user2 select * from t2;", "user2 select * from t3;"))
   872  }
   873  
   874  func (s *testBlockSuite) TestSelectHiddenDeferredCauset(c *C) {
   875  	tk := testkit.NewTestKit(c, s.causetstore)
   876  	tk.MustInterDirc("DROP DATABASE IF EXISTS `test_hidden`;")
   877  	tk.MustInterDirc("CREATE DATABASE `test_hidden`;")
   878  	tk.MustInterDirc("USE test_hidden;")
   879  	tk.MustInterDirc("CREATE TABLE hidden (a int , b int, c int);")
   880  	tk.MustQuery("select count(*) from INFORMATION_SCHEMA.COLUMNS where block_name = 'hidden'").Check(testkit.Rows("3"))
   881  	tb, err := s.dom.SchemaReplicant().BlockByName(perceptron.NewCIStr("test_hidden"), perceptron.NewCIStr("hidden"))
   882  	c.Assert(err, IsNil)
   883  	defCausInfo := tb.Meta().DeferredCausets
   884  	// Set defCausumn b to hidden
   885  	defCausInfo[1].Hidden = true
   886  	tk.MustQuery("select count(*) from INFORMATION_SCHEMA.COLUMNS where block_name = 'hidden'").Check(testkit.Rows("2"))
   887  	tk.MustQuery("select count(*) from INFORMATION_SCHEMA.COLUMNS where block_name = 'hidden' and defCausumn_name = 'b'").Check(testkit.Rows("0"))
   888  	// Set defCausumn b to visible
   889  	defCausInfo[1].Hidden = false
   890  	tk.MustQuery("select count(*) from INFORMATION_SCHEMA.COLUMNS where block_name = 'hidden' and defCausumn_name = 'b'").Check(testkit.Rows("1"))
   891  	// Set a, b ,c to hidden
   892  	defCausInfo[0].Hidden = true
   893  	defCausInfo[1].Hidden = true
   894  	defCausInfo[2].Hidden = true
   895  	tk.MustQuery("select count(*) from INFORMATION_SCHEMA.COLUMNS where block_name = 'hidden'").Check(testkit.Rows("0"))
   896  }
   897  
   898  func (s *testBlockSuite) TestFormatVersion(c *C) {
   899  	// Test for defaultVersions.
   900  	defaultVersions := []string{"5.7.25-MilevaDB-None", "5.7.25-MilevaDB-8.0.18", "5.7.25-MilevaDB-8.0.18-beta.1", "5.7.25-MilevaDB-v4.0.0-beta-446-g5268094af"}
   901  	defaultRes := []string{"None", "8.0.18", "8.0.18-beta.1", "4.0.0-beta"}
   902  	for i, v := range defaultVersions {
   903  		version := schemareplicant.FormatVersion(v, true)
   904  		c.Assert(version, Equals, defaultRes[i])
   905  	}
   906  
   907  	// Test for versions user set.
   908  	versions := []string{"8.0.18", "5.7.25-MilevaDB", "8.0.18-MilevaDB-4.0.0-beta.1"}
   909  	res := []string{"8.0.18", "5.7.25-MilevaDB", "8.0.18-MilevaDB-4.0.0-beta.1"}
   910  	for i, v := range versions {
   911  		version := schemareplicant.FormatVersion(v, false)
   912  		c.Assert(version, Equals, res[i])
   913  	}
   914  }
   915  
   916  // Test memexs_summary.
   917  func (s *testBlockSuite) TestStmtSummaryBlock(c *C) {
   918  	tk := s.newTestKitWithRoot(c)
   919  
   920  	tk.MustInterDirc("set @@milevadb_enable_defCauslect_execution_info=0;")
   921  	tk.MustQuery("select defCausumn_comment from information_schema.defCausumns " +
   922  		"where block_name='STATEMENTS_SUMMARY' and defCausumn_name='STMT_TYPE'",
   923  	).Check(testkit.Rows("Statement type"))
   924  
   925  	tk.MustInterDirc("drop causet if exists t")
   926  	tk.MustInterDirc("create causet t(a int, b varchar(10), key k(a))")
   927  
   928  	// Clear all memexs.
   929  	tk.MustInterDirc("set stochastik milevadb_enable_stmt_summary = 0")
   930  	tk.MustInterDirc("set stochastik milevadb_enable_stmt_summary = ''")
   931  
   932  	tk.MustInterDirc("set global milevadb_enable_stmt_summary = 1")
   933  	tk.MustQuery("select @@global.milevadb_enable_stmt_summary").Check(testkit.Rows("1"))
   934  
   935  	// Invalidate the cache manually so that milevadb_enable_stmt_summary works immediately.
   936  	s.dom.GetGlobalVarsCache().Disable()
   937  	// Disable refreshing summary.
   938  	tk.MustInterDirc("set global milevadb_stmt_summary_refresh_interval = 999999999")
   939  	tk.MustQuery("select @@global.milevadb_stmt_summary_refresh_interval").Check(testkit.Rows("999999999"))
   940  
   941  	// Create a new stochastik to test.
   942  	tk = s.newTestKitWithRoot(c)
   943  
   944  	// Test INSERT
   945  	tk.MustInterDirc("insert into t values(1, 'a')")
   946  	tk.MustInterDirc("insert into t    values(2, 'b')")
   947  	tk.MustInterDirc("insert into t VALUES(3, 'c')")
   948  	tk.MustInterDirc("/**/insert into t values(4, 'd')")
   949  	tk.MustQuery(`select stmt_type, schema_name, block_names, index_names, exec_count, sum_cop_task_num, avg_total_keys,
   950  		max_total_keys, avg_processed_keys, max_processed_keys, avg_write_keys, max_write_keys, avg_prewrite_regions,
   951  		max_prewrite_regions, avg_affected_rows, query_sample_text
   952  		from information_schema.memexs_summary
   953  		where digest_text like 'insert into t%'`,
   954  	).Check(testkit.Rows("Insert test test.t <nil> 4 0 0 0 0 0 2 2 1 1 1 insert into t values(1, 'a')"))
   955  
   956  	// Test point get.
   957  	tk.MustInterDirc("drop causet if exists p")
   958  	tk.MustInterDirc("create causet p(a int primary key, b int)")
   959  	for i := 1; i < 3; i++ {
   960  		tk.MustQuery("select b from p where a=1")
   961  		expectedResult := fmt.Sprintf("%d \tid         \ttask\testRows\toperator info\n\tPoint_Get_1\troot\t1      \tcauset:p, handle:1 %s", i, "test.p")
   962  		// Also make sure that the plan digest is not empty
   963  		tk.MustQuery(`select exec_count, plan, block_names
   964  			from information_schema.memexs_summary
   965  			where digest_text like 'select b from p%' and plan_digest != ''`,
   966  		).Check(testkit.Rows(expectedResult))
   967  	}
   968  
   969  	// Point get another database.
   970  	tk.MustQuery("select variable_value from allegrosql.milevadb where variable_name = 'system_tz'")
   971  	tk.MustQuery(`select block_names
   972  			from information_schema.memexs_summary
   973  			where digest_text like 'select variable_value%' and schema_name='test'`,
   974  	).Check(testkit.Rows("allegrosql.milevadb"))
   975  
   976  	// Test `create database`.
   977  	tk.MustInterDirc("create database if not exists test")
   978  	tk.MustQuery(`select block_names
   979  			from information_schema.memexs_summary
   980  			where digest_text like 'create database%' and schema_name='test'`,
   981  	).Check(testkit.Rows("<nil>"))
   982  
   983  	// Test SELECT.
   984  	const failpointName = "github.com/whtcorpsinc/milevadb/causet/embedded/mockCausetRowCount"
   985  	c.Assert(failpoint.Enable(failpointName, "return(100)"), IsNil)
   986  	defer func() { c.Assert(failpoint.Disable(failpointName), IsNil) }()
   987  	tk.MustQuery("select * from t where a=2")
   988  	tk.MustQuery(`select stmt_type, schema_name, block_names, index_names, exec_count, sum_cop_task_num, avg_total_keys,
   989  		max_total_keys, avg_processed_keys, max_processed_keys, avg_write_keys, max_write_keys, avg_prewrite_regions,
   990  		max_prewrite_regions, avg_affected_rows, query_sample_text, plan
   991  		from information_schema.memexs_summary
   992  		where digest_text like 'select * from t%'`,
   993  	).Check(testkit.Rows("Select test test.t t:k 1 2 0 0 0 0 0 0 0 0 0 select * from t where a=2 \tid            \ttask     \testRows\toperator info\n" +
   994  		"\tIndexLookUp_10\troot     \t100    \t\n" +
   995  		"\t├─IndexScan_8 \tcop[einsteindb]\t100    \tcauset:t, index:k(a), range:[2,2], keep order:false, stats:pseudo\n" +
   996  		"\t└─BlockScan_9 \tcop[einsteindb]\t100    \tcauset:t, keep order:false, stats:pseudo"))
   997  
   998  	// select ... order by
   999  	tk.MustQuery(`select stmt_type, schema_name, block_names, index_names, exec_count, sum_cop_task_num, avg_total_keys,
  1000  		max_total_keys, avg_processed_keys, max_processed_keys, avg_write_keys, max_write_keys, avg_prewrite_regions,
  1001  		max_prewrite_regions, avg_affected_rows, query_sample_text
  1002  		from information_schema.memexs_summary
  1003  		order by exec_count desc limit 1`,
  1004  	).Check(testkit.Rows("Insert test test.t <nil> 4 0 0 0 0 0 2 2 1 1 1 insert into t values(1, 'a')"))
  1005  
  1006  	// Test different plans with same digest.
  1007  	c.Assert(failpoint.Enable(failpointName, "return(1000)"), IsNil)
  1008  	tk.MustQuery("select * from t where a=3")
  1009  	tk.MustQuery(`select stmt_type, schema_name, block_names, index_names, exec_count, sum_cop_task_num, avg_total_keys,
  1010  		max_total_keys, avg_processed_keys, max_processed_keys, avg_write_keys, max_write_keys, avg_prewrite_regions,
  1011  		max_prewrite_regions, avg_affected_rows, query_sample_text, plan
  1012  		from information_schema.memexs_summary
  1013  		where digest_text like 'select * from t%'`,
  1014  	).Check(testkit.Rows("Select test test.t t:k 2 4 0 0 0 0 0 0 0 0 0 select * from t where a=2 \tid            \ttask     \testRows\toperator info\n" +
  1015  		"\tIndexLookUp_10\troot     \t100    \t\n" +
  1016  		"\t├─IndexScan_8 \tcop[einsteindb]\t100    \tcauset:t, index:k(a), range:[2,2], keep order:false, stats:pseudo\n" +
  1017  		"\t└─BlockScan_9 \tcop[einsteindb]\t100    \tcauset:t, keep order:false, stats:pseudo"))
  1018  
  1019  	// Disable it again.
  1020  	tk.MustInterDirc("set global milevadb_enable_stmt_summary = false")
  1021  	tk.MustInterDirc("set stochastik milevadb_enable_stmt_summary = false")
  1022  	defer tk.MustInterDirc("set global milevadb_enable_stmt_summary = 1")
  1023  	defer tk.MustInterDirc("set stochastik milevadb_enable_stmt_summary = ''")
  1024  	tk.MustQuery("select @@global.milevadb_enable_stmt_summary").Check(testkit.Rows("0"))
  1025  
  1026  	// Create a new stochastik to test
  1027  	tk = s.newTestKitWithRoot(c)
  1028  
  1029  	// This memex shouldn't be summarized.
  1030  	tk.MustQuery("select * from t where a=2")
  1031  
  1032  	// The causet should be cleared.
  1033  	tk.MustQuery(`select stmt_type, schema_name, block_names, index_names, exec_count, sum_cop_task_num, avg_total_keys,
  1034  		max_total_keys, avg_processed_keys, max_processed_keys, avg_write_keys, max_write_keys, avg_prewrite_regions,
  1035  		max_prewrite_regions, avg_affected_rows, query_sample_text, plan
  1036  		from information_schema.memexs_summary`,
  1037  	).Check(testkit.Rows())
  1038  
  1039  	// Enable it in stochastik scope.
  1040  	tk.MustInterDirc("set stochastik milevadb_enable_stmt_summary = on")
  1041  	// It should work immediately.
  1042  	tk.MustInterDirc("begin")
  1043  	tk.MustInterDirc("insert into t values(1, 'a')")
  1044  	tk.MustInterDirc("commit")
  1045  	tk.MustQuery(`select stmt_type, schema_name, block_names, index_names, exec_count, sum_cop_task_num, avg_total_keys,
  1046  		max_total_keys, avg_processed_keys, max_processed_keys, avg_write_keys, max_write_keys, avg_prewrite_regions,
  1047  		max_prewrite_regions, avg_affected_rows, query_sample_text, prev_sample_text
  1048  		from information_schema.memexs_summary
  1049  		where digest_text like 'insert into t%'`,
  1050  	).Check(testkit.Rows("Insert test test.t <nil> 1 0 0 0 0 0 0 0 0 0 1 insert into t values(1, 'a') "))
  1051  	tk.MustQuery(`select stmt_type, schema_name, block_names, index_names, exec_count, sum_cop_task_num, avg_total_keys,
  1052  		max_total_keys, avg_processed_keys, max_processed_keys, avg_write_keys, max_write_keys, avg_prewrite_regions,
  1053  		max_prewrite_regions, avg_affected_rows, query_sample_text, prev_sample_text
  1054  		from information_schema.memexs_summary
  1055  		where digest_text='commit'`,
  1056  	).Check(testkit.Rows("Commit test <nil> <nil> 1 0 0 0 0 0 2 2 1 1 0 commit insert into t values(1, 'a')"))
  1057  
  1058  	tk.MustQuery("select * from t where a=2")
  1059  	tk.MustQuery(`select stmt_type, schema_name, block_names, index_names, exec_count, sum_cop_task_num, avg_total_keys,
  1060  		max_total_keys, avg_processed_keys, max_processed_keys, avg_write_keys, max_write_keys, avg_prewrite_regions,
  1061  		max_prewrite_regions, avg_affected_rows, query_sample_text, plan
  1062  		from information_schema.memexs_summary
  1063  		where digest_text like 'select * from t%'`,
  1064  	).Check(testkit.Rows("Select test test.t t:k 1 2 0 0 0 0 0 0 0 0 0 select * from t where a=2 \tid            \ttask     \testRows\toperator info\n" +
  1065  		"\tIndexLookUp_10\troot     \t1000   \t\n" +
  1066  		"\t├─IndexScan_8 \tcop[einsteindb]\t1000   \tcauset:t, index:k(a), range:[2,2], keep order:false, stats:pseudo\n" +
  1067  		"\t└─BlockScan_9 \tcop[einsteindb]\t1000   \tcauset:t, keep order:false, stats:pseudo"))
  1068  
  1069  	// Disable it in global scope.
  1070  	tk.MustInterDirc("set global milevadb_enable_stmt_summary = false")
  1071  
  1072  	// Create a new stochastik to test.
  1073  	tk = s.newTestKitWithRoot(c)
  1074  
  1075  	tk.MustQuery("select * from t where a=2")
  1076  
  1077  	// Statement summary is still enabled.
  1078  	tk.MustQuery(`select stmt_type, schema_name, block_names, index_names, exec_count, sum_cop_task_num, avg_total_keys,
  1079  		max_total_keys, avg_processed_keys, max_processed_keys, avg_write_keys, max_write_keys, avg_prewrite_regions,
  1080  		max_prewrite_regions, avg_affected_rows, query_sample_text, plan
  1081  		from information_schema.memexs_summary
  1082  		where digest_text like 'select * from t%'`,
  1083  	).Check(testkit.Rows("Select test test.t t:k 2 4 0 0 0 0 0 0 0 0 0 select * from t where a=2 \tid            \ttask     \testRows\toperator info\n" +
  1084  		"\tIndexLookUp_10\troot     \t1000   \t\n" +
  1085  		"\t├─IndexScan_8 \tcop[einsteindb]\t1000   \tcauset:t, index:k(a), range:[2,2], keep order:false, stats:pseudo\n" +
  1086  		"\t└─BlockScan_9 \tcop[einsteindb]\t1000   \tcauset:t, keep order:false, stats:pseudo"))
  1087  
  1088  	// Unset stochastik variable.
  1089  	tk.MustInterDirc("set stochastik milevadb_enable_stmt_summary = ''")
  1090  	tk.MustQuery("select * from t where a=2")
  1091  
  1092  	// Statement summary is disabled.
  1093  	tk.MustQuery(`select stmt_type, schema_name, block_names, index_names, exec_count, sum_cop_task_num, avg_total_keys,
  1094  		max_total_keys, avg_processed_keys, max_processed_keys, avg_write_keys, max_write_keys, avg_prewrite_regions,
  1095  		max_prewrite_regions, avg_affected_rows, query_sample_text, plan
  1096  		from information_schema.memexs_summary`,
  1097  	).Check(testkit.Rows())
  1098  
  1099  	// Create a new stochastik to test
  1100  	tk = s.newTestKitWithRoot(c)
  1101  
  1102  	tk.MustInterDirc("set global milevadb_enable_stmt_summary = on")
  1103  	tk.MustInterDirc("set global milevadb_stmt_summary_history_size = 24")
  1104  
  1105  	// Create a new user to test memexs summary causet privilege
  1106  	tk.MustInterDirc("create user 'test_user'@'localhost'")
  1107  	tk.MustInterDirc("grant select on *.* to 'test_user'@'localhost'")
  1108  	tk.Se.Auth(&auth.UserIdentity{
  1109  		Username:     "root",
  1110  		Hostname:     "%",
  1111  		AuthUsername: "root",
  1112  		AuthHostname: "%",
  1113  	}, nil, nil)
  1114  	tk.MustInterDirc("select * from t where a=1")
  1115  	result := tk.MustQuery(`select *
  1116  		from information_schema.memexs_summary
  1117  		where digest_text like 'select * from t%'`,
  1118  	)
  1119  	// Super user can query all records.
  1120  	c.Assert(len(result.Rows()), Equals, 1)
  1121  	result = tk.MustQuery(`select *
  1122  		from information_schema.memexs_summary_history
  1123  		where digest_text like 'select * from t%'`,
  1124  	)
  1125  	c.Assert(len(result.Rows()), Equals, 1)
  1126  	tk.Se.Auth(&auth.UserIdentity{
  1127  		Username:     "test_user",
  1128  		Hostname:     "localhost",
  1129  		AuthUsername: "test_user",
  1130  		AuthHostname: "localhost",
  1131  	}, nil, nil)
  1132  	result = tk.MustQuery(`select *
  1133  		from information_schema.memexs_summary
  1134  		where digest_text like 'select * from t%'`,
  1135  	)
  1136  	// Ordinary users can not see others' records
  1137  	c.Assert(len(result.Rows()), Equals, 0)
  1138  	result = tk.MustQuery(`select *
  1139  		from information_schema.memexs_summary_history
  1140  		where digest_text like 'select * from t%'`,
  1141  	)
  1142  	c.Assert(len(result.Rows()), Equals, 0)
  1143  	tk.MustInterDirc("select * from t where a=1")
  1144  	result = tk.MustQuery(`select *
  1145  		from information_schema.memexs_summary
  1146  		where digest_text like 'select * from t%'`,
  1147  	)
  1148  	c.Assert(len(result.Rows()), Equals, 1)
  1149  	tk.MustInterDirc("select * from t where a=1")
  1150  	result = tk.MustQuery(`select *
  1151  		from information_schema.memexs_summary_history
  1152  		where digest_text like 'select * from t%'`,
  1153  	)
  1154  	c.Assert(len(result.Rows()), Equals, 1)
  1155  	// use root user to set variables back
  1156  	tk.Se.Auth(&auth.UserIdentity{
  1157  		Username:     "root",
  1158  		Hostname:     "%",
  1159  		AuthUsername: "root",
  1160  		AuthHostname: "%",
  1161  	}, nil, nil)
  1162  }
  1163  
  1164  func (s *testBlockSuite) TestIssue18845(c *C) {
  1165  	tk := testkit.NewTestKit(c, s.causetstore)
  1166  	tk.MustInterDirc(`CREATE USER 'user18845'@'localhost';`)
  1167  	tk.Se.Auth(&auth.UserIdentity{
  1168  		Username:     "user18845",
  1169  		Hostname:     "localhost",
  1170  		AuthUsername: "user18845",
  1171  		AuthHostname: "localhost",
  1172  	}, nil, nil)
  1173  	tk.MustQuery(`select count(*) from information_schema.defCausumns;`)
  1174  }
  1175  
  1176  // Test memexs_summary_history.
  1177  func (s *testBlockSuite) TestStmtSummaryHistoryBlock(c *C) {
  1178  	tk := s.newTestKitWithRoot(c)
  1179  	tk.MustInterDirc("drop causet if exists test_summary")
  1180  	tk.MustInterDirc("create causet test_summary(a int, b varchar(10), key k(a))")
  1181  
  1182  	tk.MustInterDirc("set global milevadb_enable_stmt_summary = 1")
  1183  	tk.MustQuery("select @@global.milevadb_enable_stmt_summary").Check(testkit.Rows("1"))
  1184  
  1185  	// Invalidate the cache manually so that milevadb_enable_stmt_summary works immediately.
  1186  	s.dom.GetGlobalVarsCache().Disable()
  1187  	// Disable refreshing summary.
  1188  	tk.MustInterDirc("set global milevadb_stmt_summary_refresh_interval = 999999999")
  1189  	tk.MustQuery("select @@global.milevadb_stmt_summary_refresh_interval").Check(testkit.Rows("999999999"))
  1190  
  1191  	// Create a new stochastik to test.
  1192  	tk = s.newTestKitWithRoot(c)
  1193  
  1194  	// Test INSERT
  1195  	tk.MustInterDirc("insert into test_summary values(1, 'a')")
  1196  	tk.MustInterDirc("insert into test_summary    values(2, 'b')")
  1197  	tk.MustInterDirc("insert into TEST_SUMMARY VALUES(3, 'c')")
  1198  	tk.MustInterDirc("/**/insert into test_summary values(4, 'd')")
  1199  	tk.MustQuery(`select stmt_type, schema_name, block_names, index_names, exec_count, sum_cop_task_num, avg_total_keys,
  1200  		max_total_keys, avg_processed_keys, max_processed_keys, avg_write_keys, max_write_keys, avg_prewrite_regions,
  1201  		max_prewrite_regions, avg_affected_rows, query_sample_text
  1202  		from information_schema.memexs_summary_history
  1203  		where digest_text like 'insert into test_summary%'`,
  1204  	).Check(testkit.Rows("Insert test test.test_summary <nil> 4 0 0 0 0 0 2 2 1 1 1 insert into test_summary values(1, 'a')"))
  1205  
  1206  	tk.MustInterDirc("set global milevadb_stmt_summary_history_size = 0")
  1207  	tk.MustQuery(`select stmt_type, schema_name, block_names, index_names, exec_count, sum_cop_task_num, avg_total_keys,
  1208  		max_total_keys, avg_processed_keys, max_processed_keys, avg_write_keys, max_write_keys, avg_prewrite_regions,
  1209  		max_prewrite_regions, avg_affected_rows, query_sample_text, plan
  1210  		from information_schema.memexs_summary_history`,
  1211  	).Check(testkit.Rows())
  1212  }
  1213  
  1214  // Test memexs_summary_history.
  1215  func (s *testBlockSuite) TestStmtSummaryInternalQuery(c *C) {
  1216  	tk := s.newTestKitWithRoot(c)
  1217  
  1218  	tk.MustInterDirc("drop causet if exists t")
  1219  	tk.MustInterDirc("create causet t(a int, b varchar(10), key k(a))")
  1220  
  1221  	// We use the allegrosql binding evolve to check the internal query summary.
  1222  	tk.MustInterDirc("set @@milevadb_use_plan_baselines = 1")
  1223  	tk.MustInterDirc("set @@milevadb_evolve_plan_baselines = 1")
  1224  	tk.MustInterDirc("create global binding for select * from t where t.a = 1 using select * from t ignore index(k) where t.a = 1")
  1225  	tk.MustInterDirc("set global milevadb_enable_stmt_summary = 1")
  1226  	tk.MustQuery("select @@global.milevadb_enable_stmt_summary").Check(testkit.Rows("1"))
  1227  	// Invalidate the cache manually so that milevadb_enable_stmt_summary works immediately.
  1228  	s.dom.GetGlobalVarsCache().Disable()
  1229  	// Disable refreshing summary.
  1230  	tk.MustInterDirc("set global milevadb_stmt_summary_refresh_interval = 999999999")
  1231  	tk.MustQuery("select @@global.milevadb_stmt_summary_refresh_interval").Check(testkit.Rows("999999999"))
  1232  
  1233  	// Test Internal
  1234  
  1235  	// Create a new stochastik to test.
  1236  	tk = s.newTestKitWithRoot(c)
  1237  
  1238  	tk.MustInterDirc("select * from t where t.a = 1")
  1239  	tk.MustQuery(`select exec_count, digest_text
  1240  		from information_schema.memexs_summary
  1241  		where digest_text like "select original_sql , bind_sql , default_db , status%"`).Check(testkit.Rows())
  1242  
  1243  	// Enable internal query and evolve baseline.
  1244  	tk.MustInterDirc("set global milevadb_stmt_summary_internal_query = 1")
  1245  	defer tk.MustInterDirc("set global milevadb_stmt_summary_internal_query = false")
  1246  
  1247  	// Create a new stochastik to test.
  1248  	tk = s.newTestKitWithRoot(c)
  1249  
  1250  	tk.MustInterDirc("admin flush bindings")
  1251  	tk.MustInterDirc("admin evolve bindings")
  1252  
  1253  	// `exec_count` may be bigger than 1 because other cases are also running.
  1254  	tk.MustQuery(`select digest_text
  1255  		from information_schema.memexs_summary
  1256  		where digest_text like "select original_sql , bind_sql , default_db , status%"`).Check(testkit.Rows(
  1257  		"select original_sql , bind_sql , default_db , status , create_time , uFIDelate_time , charset , defCauslation , source from allegrosql . bind_info" +
  1258  			" where uFIDelate_time > ? order by uFIDelate_time"))
  1259  }
  1260  
  1261  // Test error count and warning count.
  1262  func (s *testBlockSuite) TestStmtSummaryErrorCount(c *C) {
  1263  	tk := s.newTestKitWithRoot(c)
  1264  
  1265  	// Clear summaries.
  1266  	tk.MustInterDirc("set global milevadb_enable_stmt_summary = 0")
  1267  	tk.MustInterDirc("set global milevadb_enable_stmt_summary = 1")
  1268  
  1269  	tk.MustInterDirc("use test")
  1270  	tk.MustInterDirc("drop causet if exists stmt_summary_test")
  1271  	tk.MustInterDirc("create causet stmt_summary_test(id int primary key)")
  1272  	tk.MustInterDirc("insert into stmt_summary_test values(1)")
  1273  	_, err := tk.InterDirc("insert into stmt_summary_test values(1)")
  1274  	c.Assert(err, NotNil)
  1275  
  1276  	tk.MustQuery(`select exec_count, sum_errors, sum_warnings
  1277  		from information_schema.memexs_summary
  1278  		where digest_text like "insert into stmt_summary_test%"`).Check(testkit.Rows("2 1 0"))
  1279  
  1280  	tk.MustInterDirc("insert ignore into stmt_summary_test values(1)")
  1281  	tk.MustQuery(`select exec_count, sum_errors, sum_warnings
  1282  		from information_schema.memexs_summary
  1283  		where digest_text like "insert ignore into stmt_summary_test%"`).Check(testkit.Rows("1 0 1"))
  1284  }
  1285  
  1286  func (s *testBlockSuite) TestStmtSummaryPreparedStatements(c *C) {
  1287  	tk := s.newTestKitWithRoot(c)
  1288  
  1289  	// Clear summaries.
  1290  	tk.MustInterDirc("set global milevadb_enable_stmt_summary = 0")
  1291  	tk.MustInterDirc("set global milevadb_enable_stmt_summary = 1")
  1292  
  1293  	tk.MustInterDirc("use test")
  1294  	tk.MustInterDirc("prepare stmt from 'select ?'")
  1295  	tk.MustInterDirc("set @number=1")
  1296  	tk.MustInterDirc("execute stmt using @number")
  1297  
  1298  	tk.MustQuery(`select exec_count
  1299  		from information_schema.memexs_summary
  1300  		where digest_text like "prepare%"`).Check(testkit.Rows())
  1301  	tk.MustQuery(`select exec_count
  1302  		from information_schema.memexs_summary
  1303  		where digest_text like "select ?"`).Check(testkit.Rows("1"))
  1304  }
  1305  
  1306  func (s *testBlockSuite) TestStmtSummarySensitiveQuery(c *C) {
  1307  	tk := s.newTestKitWithRoot(c)
  1308  	tk.MustInterDirc("set global milevadb_enable_stmt_summary = 0")
  1309  	tk.MustInterDirc("set global milevadb_enable_stmt_summary = 1")
  1310  	tk.MustInterDirc("drop user if exists user_sensitive;")
  1311  	tk.MustInterDirc("create user user_sensitive identified by '123456789';")
  1312  	tk.MustInterDirc("alter user 'user_sensitive'@'%' identified by 'abcdefg';")
  1313  	tk.MustInterDirc("set password for 'user_sensitive'@'%' = 'xyzuvw';")
  1314  	tk.MustQuery("select query_sample_text from `information_schema`.`STATEMENTS_SUMMARY` " +
  1315  		"where query_sample_text like '%user_sensitive%' and " +
  1316  		"(query_sample_text like 'set password%' or query_sample_text like 'create user%' or query_sample_text like 'alter user%') " +
  1317  		"order by query_sample_text;").
  1318  		Check(testkit.Rows(
  1319  			"alter user {user_sensitive@% password = ***}",
  1320  			"create user {user_sensitive@% password = ***}",
  1321  			"set password for user user_sensitive@%",
  1322  		))
  1323  }
  1324  
  1325  func (s *testBlockSuite) TestPerformanceSchemaforCausetCache(c *C) {
  1326  	orgEnable := causetembedded.PreparedCausetCacheEnabled()
  1327  	defer func() {
  1328  		causetembedded.SetPreparedCausetCache(orgEnable)
  1329  	}()
  1330  	causetembedded.SetPreparedCausetCache(true)
  1331  
  1332  	tk := s.newTestKitWithCausetCache(c)
  1333  
  1334  	// Clear summaries.
  1335  	tk.MustInterDirc("set global milevadb_enable_stmt_summary = 0")
  1336  	tk.MustInterDirc("set global milevadb_enable_stmt_summary = 1")
  1337  	tk.MustInterDirc("use test")
  1338  	tk.MustInterDirc("drop causet if exists t")
  1339  	tk.MustInterDirc("create causet t(a int)")
  1340  	tk.MustInterDirc("prepare stmt from 'select * from t'")
  1341  	tk.MustInterDirc("execute stmt")
  1342  	tk.MustQuery("select plan_cache_hits, plan_in_cache from information_schema.memexs_summary where digest_text='select * from t'").Check(
  1343  		testkit.Rows("0 0"))
  1344  	tk.MustInterDirc("execute stmt")
  1345  	tk.MustInterDirc("execute stmt")
  1346  	tk.MustInterDirc("execute stmt")
  1347  	tk.MustQuery("select plan_cache_hits, plan_in_cache from information_schema.memexs_summary where digest_text='select * from t'").Check(
  1348  		testkit.Rows("3 1"))
  1349  }