Example #1
0
func (ts *testMemoryTableSuite) SetUpSuite(c *C) {
	driver := localstore.Driver{Driver: goleveldb.MemoryDriver{}}
	store, err := driver.Open("memory")
	c.Check(err, IsNil)
	ts.store = store
	ts.se, err = tidb.CreateSession(ts.store)
	c.Assert(err, IsNil)

	// create table
	tp1 := types.NewFieldType(mysql.TypeLong)
	col1 := &model.ColumnInfo{
		ID:        1,
		Name:      model.NewCIStr("a"),
		Offset:    0,
		FieldType: *tp1,
	}
	tp2 := types.NewFieldType(mysql.TypeVarchar)
	tp2.Flen = 255
	col2 := &model.ColumnInfo{
		ID:        2,
		Name:      model.NewCIStr("b"),
		Offset:    1,
		FieldType: *tp2,
	}

	tblInfo := &model.TableInfo{
		ID:      100,
		Name:    model.NewCIStr("t"),
		Columns: []*model.ColumnInfo{col1, col2},
	}
	alloc := autoid.NewMemoryAllocator(int64(10))
	ts.tbl, _ = tables.MemoryTableFromMeta(alloc, tblInfo)
}
Example #2
0
// NewGCWorker creates a GCWorker instance.
func NewGCWorker(store kv.Storage) (*GCWorker, error) {
	session, err := tidb.CreateSession(store)
	if err != nil {
		return nil, errors.Trace(err)
	}
	ver, err := store.CurrentVersion()
	if err != nil {
		return nil, errors.Trace(err)
	}
	hostName, err := os.Hostname()
	if err != nil {
		hostName = "unknown"
	}
	worker := &GCWorker{
		uuid:        strconv.FormatUint(ver.Ver, 16),
		desc:        fmt.Sprintf("host:%s, pid:%d, start at %s", hostName, os.Getpid(), time.Now()),
		store:       store.(*tikvStore),
		session:     session,
		gcIsRunning: false,
		lastFinish:  time.Now(),
		quit:        make(chan struct{}),
		done:        make(chan error),
	}
	go worker.start()
	return worker, nil
}
Example #3
0
func (ts *testSuite) TestConstraintNames(c *C) {
	se, _ := tidb.CreateSession(ts.store)
	ctx := se.(context.Context)
	schemaName := model.NewCIStr("test_constraint")
	tblName := model.NewCIStr("t")
	tbIdent := table.Ident{
		Schema: schemaName,
		Name:   tblName,
	}

	err := sessionctx.GetDomain(ctx).DDL().CreateSchema(ctx, tbIdent.Schema, ts.charsetInfo)
	c.Assert(err, IsNil)

	tbStmt := statement(ctx, "create table t (a int, b int, index a (a, b), index a (a))").(*stmts.CreateTableStmt)
	err = sessionctx.GetDomain(ctx).DDL().CreateTable(ctx, tbIdent, tbStmt.Cols, tbStmt.Constraints)
	c.Assert(err, NotNil)

	tbStmt = statement(ctx, "create table t (a int, b int, index A (a, b), index (a))").(*stmts.CreateTableStmt)
	err = sessionctx.GetDomain(ctx).DDL().CreateTable(ctx, tbIdent, tbStmt.Cols, tbStmt.Constraints)
	c.Assert(err, IsNil)
	tbl, err := sessionctx.GetDomain(ctx).InfoSchema().TableByName(schemaName, tblName)
	indices := tbl.Indices()
	c.Assert(len(indices), Equals, 2)
	c.Assert(indices[0].Name.O, Equals, "A")
	c.Assert(indices[1].Name.O, Equals, "a_2")

	err = sessionctx.GetDomain(ctx).DDL().DropSchema(ctx, tbIdent.Schema)
	c.Assert(err, IsNil)
}
Example #4
0
func newSession(c *C, store kv.Storage, dbName string) tidb.Session {
	se, err := tidb.CreateSession(store)
	c.Assert(err, IsNil)
	mustExecSQL(c, se, "create database if not exists "+dbName)
	mustExecSQL(c, se, "use "+dbName)
	return se
}
Example #5
0
func (s *testStoreSuite) TestBusyServerCop(c *C) {
	client := newBusyClient(s.store.client)
	s.store.client = client

	session, err := tidb.CreateSession(s.store)
	c.Assert(err, IsNil)

	var wg sync.WaitGroup
	wg.Add(2)

	client.setBusy(true)
	go func() {
		defer wg.Done()
		time.Sleep(time.Millisecond * 100)
		client.setBusy(false)
	}()

	go func() {
		defer wg.Done()
		rs, err := session.Execute(`SELECT variable_value FROM mysql.tidb WHERE variable_name="bootstrapped"`)
		c.Assert(err, IsNil)
		row, err := rs[0].Next()
		c.Assert(err, IsNil)
		c.Assert(row, NotNil)
		c.Assert(row.Data[0].GetString(), Equals, "True")
	}()

	wg.Wait()
}
Example #6
0
func (ts *testSuite) TestConstraintNames(c *C) {
	handle := infoschema.NewHandle(ts.store)
	handle.Set(nil)
	dd := ddl.NewDDL(ts.store, handle)
	se, _ := tidb.CreateSession(ts.store)
	ctx := se.(context.Context)
	schemaName := model.NewCIStr("test")
	tblName := model.NewCIStr("t")
	tbIdent := table.Ident{
		Schema: schemaName,
		Name:   tblName,
	}
	err := dd.CreateSchema(ctx, tbIdent.Schema)
	c.Assert(err, IsNil)
	tbStmt := statement("create table t (a int, b int, index a (a, b), index a (a))").(*stmts.CreateTableStmt)
	err = dd.CreateTable(ctx, tbIdent, tbStmt.Cols, tbStmt.Constraints)
	c.Assert(err, NotNil)

	tbStmt = statement("create table t (a int, b int, index A (a, b), index (a))").(*stmts.CreateTableStmt)
	err = dd.CreateTable(ctx, tbIdent, tbStmt.Cols, tbStmt.Constraints)
	c.Assert(err, IsNil)
	tbl, err := handle.Get().TableByName(schemaName, tblName)
	indices := tbl.Indices()
	c.Assert(len(indices), Equals, 2)
	c.Assert(indices[0].Name.O, Equals, "A")
	c.Assert(indices[1].Name.O, Equals, "a_2")

	err = dd.DropSchema(ctx, tbIdent.Schema)
	c.Assert(err, IsNil)
}
Example #7
0
func (s *testSuite) TestSetPwd(c *C) {
	defer testleak.AfterTest(c)()
	tk := testkit.NewTestKit(c, s.store)

	createUserSQL := `CREATE USER 'testpwd'@'localhost' IDENTIFIED BY '';`
	tk.MustExec(createUserSQL)
	result := tk.MustQuery(`SELECT Password FROM mysql.User WHERE User="******" and Host="localhost"`)
	rowStr := fmt.Sprintf("%v", []byte(""))
	result.Check(testkit.Rows(rowStr))

	// set password for
	tk.MustExec(`SET PASSWORD FOR 'testpwd'@'localhost' = 'password';`)
	result = tk.MustQuery(`SELECT Password FROM mysql.User WHERE User="******" and Host="localhost"`)
	rowStr = fmt.Sprintf("%v", []byte(util.EncodePassword("password")))
	result.Check(testkit.Rows(rowStr))

	// set password
	setPwdSQL := `SET PASSWORD = '******'`
	// Session user is empty.
	_, err := tk.Exec(setPwdSQL)
	c.Check(err, NotNil)
	tk.Se, err = tidb.CreateSession(s.store)
	c.Check(err, IsNil)
	ctx := tk.Se.(context.Context)
	ctx.GetSessionVars().User = "******"
	// Session user doesn't exist.
	_, err = tk.Exec(setPwdSQL)
	c.Check(terror.ErrorEqual(err, executor.ErrPasswordNoMatch), IsTrue)
	// normal
	ctx.GetSessionVars().User = "******"
	tk.MustExec(setPwdSQL)
	result = tk.MustQuery(`SELECT Password FROM mysql.User WHERE User="******" and Host="localhost"`)
	rowStr = fmt.Sprintf("%v", []byte(util.EncodePassword("pwd")))
	result.Check(testkit.Rows(rowStr))
}
Example #8
0
// Exec executes a sql statement.
func (tk *TestKit) Exec(sql string, args ...interface{}) (ast.RecordSet, error) {
	var err error
	if tk.Se == nil {
		tk.Se, err = tidb.CreateSession(tk.store)
		tk.c.Assert(err, check.IsNil)
	}
	if len(args) == 0 {
		var rss []ast.RecordSet
		rss, err = tk.Se.Execute(sql)
		if err == nil && len(rss) > 0 {
			return rss[0], nil
		}
		return nil, err
	}
	stmtID, _, _, err := tk.Se.PrepareStmt(sql)
	if err != nil {
		return nil, err
	}
	rs, err := tk.Se.ExecutePreparedStmt(stmtID, args...)
	if err != nil {
		return nil, err
	}
	err = tk.Se.DropPreparedStmt(stmtID)
	if err != nil {
		return nil, err
	}
	return rs, nil
}
Example #9
0
func (s *testValidatorSuite) TestValidator(c *C) {
	cases := []struct {
		sql       string
		inPrepare bool
		err       error
	}{
		{"select ?", false, parser.ErrSyntax},
		{"select ?", true, nil},
		{"create table t(id int not null auto_increment default 2, key (id))", true,
			errors.New("Invalid default value for 'id'")},
		{"create table t(id int not null default 2 auto_increment, key (id))", true,
			errors.New("Invalid default value for 'id'")},
		{"create table t(id int not null auto_increment)", true,
			errors.New("Incorrect table definition; there can be only one auto column and it must be defined as a key")},
		{"create table t(id int not null auto_increment, c int auto_increment, key (id, c))", true,
			errors.New("Incorrect table definition; there can be only one auto column and it must be defined as a key")},
		{"create table t(id int not null auto_increment, c int, key (c, id))", true,
			errors.New("Incorrect table definition; there can be only one auto column and it must be defined as a key")},
		{"create table t(id decimal auto_increment, key (id))", true,
			errors.New("Incorrect column specifier for column 'id'")},
		{"create table t(id float auto_increment, key (id))", true, nil},
	}
	store, err := tidb.NewStore(tidb.EngineGoLevelDBMemory)
	c.Assert(err, IsNil)
	se, err := tidb.CreateSession(store)
	c.Assert(err, IsNil)
	for _, ca := range cases {
		stmts, err1 := tidb.Parse(se.(context.Context), ca.sql)
		c.Assert(err1, IsNil)
		c.Assert(stmts, HasLen, 1)
		stmt := stmts[0]
		err = optimizer.Validate(stmt, ca.inPrepare)
		c.Assert(terror.ErrorEqual(err, ca.err), IsTrue)
	}
}
Example #10
0
func (s *testDBSuite) SetUpSuite(c *C) {
	trySkipDBTest(c)

	var err error

	s.schemaName = "test_db"

	uri := "memory://test"
	s.store, err = tidb.NewStore(uri)
	c.Assert(err, IsNil)

	s.db, err = sql.Open("tidb", fmt.Sprintf("%s/%s", uri, s.schemaName))
	c.Assert(err, IsNil)

	s.s, err = tidb.CreateSession(s.store)
	c.Assert(err, IsNil)

	s.mustExec(c, "create table t1 (c1 int, c2 int, c3 int, primary key(c1))")
	s.mustExec(c, "create table t2 (c1 int, c2 int, c3 int)")

	// set proper schema lease
	s.lease = 500 * time.Millisecond
	ctx := s.s.(context.Context)
	sessionctx.GetDomain(ctx).SetLease(s.lease)
}
Example #11
0
File: main.go Project: anywhy/tidb
func main() {
	tidb.RegisterLocalStore("boltdb", boltdb.Driver{})
	tidb.RegisterStore("tikv", tikv.Driver{})

	metric.RunMetric(3 * time.Second)
	printer.PrintTiDBInfo()
	runtime.GOMAXPROCS(runtime.NumCPU())

	flag.Parse()

	if *lease < 0 {
		log.Fatalf("invalid lease seconds %d", *lease)
	}

	tidb.SetSchemaLease(time.Duration(*lease) * time.Second)

	cfg := &server.Config{
		Addr:       fmt.Sprintf(":%s", *port),
		LogLevel:   *logLevel,
		StatusAddr: fmt.Sprintf(":%s", *statusPort),
		Socket:     *socket,
	}

	log.SetLevelByString(cfg.LogLevel)
	store, err := tidb.NewStore(fmt.Sprintf("%s://%s", *store, *storePath))
	if err != nil {
		log.Fatal(errors.ErrorStack(err))
	}
	// Create a session to load information schema.
	se, err := tidb.CreateSession(store)
	if err != nil {
		log.Fatal(errors.ErrorStack(err))
	}
	se.Close()

	var driver server.IDriver
	driver = server.NewTiDBDriver(store)
	var svr *server.Server
	svr, err = server.NewServer(cfg, driver)
	if err != nil {
		log.Fatal(errors.ErrorStack(err))
	}

	sc := make(chan os.Signal, 1)
	signal.Notify(sc,
		syscall.SIGHUP,
		syscall.SIGINT,
		syscall.SIGTERM,
		syscall.SIGQUIT)

	go func() {
		sig := <-sc
		log.Infof("Got signal [%d] to exit.", sig)
		svr.Close()
		os.Exit(0)
	}()

	log.Error(svr.Run())
}
Example #12
0
func (ts *testSuite) SetUpSuite(c *C) {
	driver := localstore.Driver{Driver: goleveldb.MemoryDriver{}}
	store, err := driver.Open("memory")
	c.Check(err, IsNil)
	ts.store = store
	ts.se, err = tidb.CreateSession(ts.store)
	c.Assert(err, IsNil)
}
Example #13
0
func sessionExec(c *C, s kv.Storage, sql string) {
	se, err := tidb.CreateSession(s)
	c.Assert(err, IsNil)
	_, err = se.Execute("use test_db")
	rs, err := se.Execute(sql)
	c.Assert(err, IsNil, Commentf("err:%v", errors.ErrorStack(err)))
	c.Assert(rs, IsNil)
	se.Close()
}
Example #14
0
func (ts *testSuite) SetUpSuite(c *C) {
	table.TableFromMeta = tables.TableFromMeta
	driver := localstore.Driver{goleveldb.MemoryDriver{}}
	store, err := driver.Open("memory")
	c.Check(err, IsNil)
	ts.store = store
	ts.se, err = tidb.CreateSession(ts.store)
	c.Assert(err, IsNil)
	_, err = ts.se.Execute("CREATE DATABASE test")
	c.Assert(err, IsNil)
}
Example #15
0
func (p *testIndexSuit) SetUpSuite(c *C) {
	store, err := tidb.NewStore(tidb.EngineGoLevelDBMemory)
	c.Assert(err, IsNil)
	p.store = store
	se, _ := tidb.CreateSession(store)
	p.ctx = se.(context.Context)
	p.cols = []*column.Col{
		{
			ColumnInfo: model.ColumnInfo{
				ID:           0,
				Name:         model.NewCIStr("id"),
				Offset:       0,
				DefaultValue: 0,
				FieldType:    *types.NewFieldType(mysql.TypeLonglong),
				State:        model.StatePublic,
			},
		},
		{
			ColumnInfo: model.ColumnInfo{
				ID:           1,
				Name:         model.NewCIStr("name"),
				Offset:       1,
				DefaultValue: nil,
				FieldType:    *types.NewFieldType(mysql.TypeVarchar),
				State:        model.StatePublic,
			},
		},
	}
	p.tbl = tables.NewTable(2, "t2", p.cols, &simpleAllocator{})

	idxCol := &column.IndexedCol{
		IndexInfo: model.IndexInfo{
			Name:  model.NewCIStr("id"),
			Table: model.NewCIStr("t2"),
			Columns: []*model.IndexColumn{
				{
					Name:   model.NewCIStr("id"),
					Offset: 0,
					Length: 0,
				},
			},
			Unique:  false,
			Primary: false,
			State:   model.StatePublic,
		},
		X: kv.NewKVIndex("i", "id", 0, false),
	}
	p.tbl.AddIndex(idxCol)
	var i int64
	for i = 0; i < 10; i++ {
		p.tbl.AddRecord(p.ctx, []interface{}{i * 10, "hello"}, 0)
	}
}
Example #16
0
func (p *testIndexSuit) SetUpSuite(c *C) {
	store, err := tidb.NewStore(tidb.EngineGoLevelDBMemory)
	c.Assert(err, IsNil)
	p.store = store
	se, _ := tidb.CreateSession(store)
	p.ctx = se.(context.Context)
	tbInfo := &model.TableInfo{
		ID:    2,
		Name:  model.NewCIStr("t2"),
		State: model.StatePublic,
		Columns: []*model.ColumnInfo{
			{
				ID:           0,
				Name:         model.NewCIStr("id"),
				Offset:       0,
				DefaultValue: 0,
				FieldType:    *types.NewFieldType(mysql.TypeLonglong),
				State:        model.StatePublic,
			},
			{
				ID:           1,
				Name:         model.NewCIStr("name"),
				Offset:       1,
				DefaultValue: nil,
				FieldType:    *types.NewFieldType(mysql.TypeVarchar),
				State:        model.StatePublic,
			},
		},
		Indices: []*model.IndexInfo{
			{
				Name:  model.NewCIStr("id"),
				Table: model.NewCIStr("t2"),
				Columns: []*model.IndexColumn{
					{
						Name:   model.NewCIStr("id"),
						Offset: 0,
						Length: 0,
					},
				},
				Unique:  false,
				Primary: false,
				State:   model.StatePublic,
			},
		},
	}

	p.tbl, err = tables.TableFromMeta(&simpleAllocator{}, tbInfo)
	c.Assert(err, IsNil)
	var i int64
	for i = 0; i < 10; i++ {
		p.tbl.AddRecord(p.ctx, []interface{}{i * 10, "hello"})
	}
}
Example #17
0
func newSession(c *C, store kv.Storage, dbName string) tidb.Session {
	se, err := tidb.CreateSession(store)
	c.Assert(err, IsNil)
	id := atomic.AddUint64(&testConnID, 1)
	se.SetConnectionID(id)
	c.Assert(err, IsNil)
	se.Auth(`root@%`, nil, []byte("012345678901234567890"))
	if len(dbName) != 0 {
		mustExecSQL(c, se, "create database if not exists "+dbName)
		mustExecSQL(c, se, "use "+dbName)
	}
	return se
}
Example #18
0
func backgroundExec(s kv.Storage, sql string, done chan error) {
	se, err := tidb.CreateSession(s)
	if err != nil {
		done <- errors.Trace(err)
		return
	}
	defer se.Close()
	_, err = se.Execute("use test_db")
	if err != nil {
		done <- errors.Trace(err)
		return
	}
	_, err = se.Execute(sql)
	done <- errors.Trace(err)
}
Example #19
0
// OpenCtx implements IDriver.
func (qd *TiDBDriver) OpenCtx(capability uint32, collation uint8, dbname string) (IContext, error) {
	session, _ := tidb.CreateSession(qd.store)
	session.SetClientCapability(capability)
	if dbname != "" {
		_, err := session.Execute("use " + dbname)
		if err != nil {
			return nil, err
		}
	}
	tc := &TiDBContext{
		session:   session,
		currentDB: dbname,
		stmts:     make(map[int]*TiDBStatement),
	}
	return tc, nil
}
Example #20
0
func (*testSuite) TestT(c *C) {
	var ident = ast.Ident{
		Name: model.NewCIStr("t"),
	}
	c.Assert(ident.String(), Not(Equals), "")
	driver := localstore.Driver{Driver: goleveldb.MemoryDriver{}}
	store, err := driver.Open("memory")
	c.Assert(err, IsNil)
	se, err := tidb.CreateSession(store)
	c.Assert(err, IsNil)
	ctx := se.(context.Context)
	db.BindCurrentSchema(ctx, "test")
	fullIdent := ident.Full(ctx)
	c.Assert(fullIdent.Schema.L, Equals, "test")
	c.Assert(fullIdent.Name.L, Equals, "t")
	c.Assert(fullIdent.String(), Not(Equals), "")
	fullIdent2 := fullIdent.Full(ctx)
	c.Assert(fullIdent2.Schema.L, Equals, fullIdent.Schema.L)
}
Example #21
0
// NewGCWorker creates a GCWorker instance.
func NewGCWorker(store *tikvStore) (*GCWorker, error) {
	session, err := tidb.CreateSession(store)
	if err != nil {
		return nil, errors.Trace(err)
	}
	ver, err := store.CurrentVersion()
	if err != nil {
		return nil, errors.Trace(err)
	}
	worker := &GCWorker{
		uuid:    fmt.Sprintf("gcworker_%d", ver.Ver),
		store:   store,
		session: session,
		quit:    make(chan struct{}),
		done:    make(chan error),
	}
	go worker.start(ver.Ver)
	return worker, nil
}
Example #22
0
func (s *testSuite) TestAdapterStatement(c *C) {
	defer testleak.AfterTest(c)()
	se, err := tidb.CreateSession(s.store)
	c.Check(err, IsNil)
	compiler := &executor.Compiler{}
	ctx := se.(context.Context)

	stmtNode, err := s.ParseOneStmt("select 1", "", "")
	c.Check(err, IsNil)
	stmt, err := compiler.Compile(ctx, stmtNode)
	c.Check(err, IsNil)
	c.Check(stmt.OriginText(), Equals, "select 1")
	c.Check(stmt.IsDDL(), IsFalse)

	stmtNode, err = s.ParseOneStmt("create table t (a int)", "", "")
	c.Check(err, IsNil)
	stmt, err = compiler.Compile(ctx, stmtNode)
	c.Check(err, IsNil)
	c.Check(stmt.OriginText(), Equals, "create table t (a int)")
}
Example #23
0
func (s *testValidatorSuite) TestValidator(c *C) {
	defer testleak.AfterTest(c)()
	cases := []struct {
		sql       string
		inPrepare bool
		err       error
	}{
		{"select ?", false, parser.ErrSyntax},
		{"select ?", true, nil},
		{"create table t(id int not null auto_increment default 2, key (id))", true,
			errors.New("Invalid default value for 'id'")},
		{"create table t(id int not null default 2 auto_increment, key (id))", true,
			errors.New("Invalid default value for 'id'")},
		{"create table t(id int not null auto_increment)", true,
			errors.New("Incorrect table definition; there can be only one auto column and it must be defined as a key")},
		{"create table t(id int not null auto_increment, c int auto_increment, key (id, c))", true,
			errors.New("Incorrect table definition; there can be only one auto column and it must be defined as a key")},
		{"create table t(id int not null auto_increment, c int, key (c, id))", true,
			errors.New("Incorrect table definition; there can be only one auto column and it must be defined as a key")},
		{"create table t(id decimal auto_increment, key (id))", true,
			errors.New("Incorrect column specifier for column 'id'")},
		{"create table t(id float auto_increment, key (id))", true, nil},
		{"create table t(id int auto_increment) ENGINE=MYISAM", true, nil},
		{"create table t(a int primary key, b int, c varchar(10), d char(256));", true, errors.New("Column length too big for column 'd' (max = 255); use BLOB or TEXT instead")},
		{"create index ib on t(b,a,b);", true, errors.New("Duplicate column name 'b'")},
		{"create table t(c1 int not null primary key, c2 int not null primary key)", true, errors.New("Multiple primary key defined")},
	}
	store, err := tidb.NewStore(tidb.EngineGoLevelDBMemory)
	c.Assert(err, IsNil)
	defer store.Close()
	se, err := tidb.CreateSession(store)
	c.Assert(err, IsNil)
	for _, ca := range cases {
		stmts, err1 := tidb.Parse(se.(context.Context), ca.sql)
		c.Assert(err1, IsNil)
		c.Assert(stmts, HasLen, 1)
		stmt := stmts[0]
		err = plan.Validate(stmt, ca.inPrepare)
		c.Assert(terror.ErrorEqual(err, ca.err), IsTrue)
	}
}
Example #24
0
func (s *testDBSuite) SetUpSuite(c *C) {
	var err error

	s.lease = 100 * time.Millisecond
	tidb.SetSchemaLease(s.lease)
	s.schemaName = "test_db"
	s.store, err = tidb.NewStore(tidb.EngineGoLevelDBMemory)
	c.Assert(err, IsNil)
	localstore.MockRemoteStore = true
	s.s, err = tidb.CreateSession(s.store)
	c.Assert(err, IsNil)

	_, err = s.s.Execute("create database test_db")
	c.Assert(err, IsNil)
	_, err = s.s.Execute("use " + s.schemaName)
	c.Assert(err, IsNil)
	_, err = s.s.Execute("create table t1 (c1 int, c2 int, c3 int, primary key(c1))")
	c.Assert(err, IsNil)
	_, err = s.s.Execute("create table t2 (c1 int, c2 int, c3 int)")
	c.Assert(err, IsNil)
}
Example #25
0
func (s *testValidatorSuite) TestValidator(c *C) {
	cases := []struct {
		sql       string
		inPrepare bool
		err       error
	}{
		{"select ?", false, parser.ErrSyntax},
		{"select ?", true, nil},
	}
	store, err := tidb.NewStore(tidb.EngineGoLevelDBMemory)
	c.Assert(err, IsNil)
	se, err := tidb.CreateSession(store)
	c.Assert(err, IsNil)
	for _, ca := range cases {
		stmts, err1 := tidb.Parse(se.(context.Context), ca.sql)
		c.Assert(err1, IsNil)
		c.Assert(stmts, HasLen, 1)
		stmt := stmts[0]
		err = optimizer.Validate(stmt, ca.inPrepare)
		c.Assert(terror.ErrorEqual(err, ca.err), IsTrue)
	}
}
Example #26
0
func (t *testLimitSuit) SetUpSuite(c *C) {
	store, _ := tidb.NewStore(tidb.EngineGoLevelDBMemory)
	t.sess, _ = tidb.CreateSession(store)
}
Example #27
0
func (ts *testSuite) TestT(c *C) {
	handle := infoschema.NewHandle(ts.store)
	handle.Set(nil)
	dd := ddl.NewDDL(ts.store, handle)
	se, _ := tidb.CreateSession(ts.store)
	ctx := se.(context.Context)
	schemaName := model.NewCIStr("test")
	tblName := model.NewCIStr("t")
	tbIdent := table.Ident{
		Schema: schemaName,
		Name:   tblName,
	}
	noExist := model.NewCIStr("noexist")

	err := dd.CreateSchema(ctx, tbIdent.Schema)
	c.Assert(err, IsNil)

	err = dd.CreateSchema(ctx, tbIdent.Schema)
	c.Assert(errors2.ErrorEqual(err, ddl.ErrExists), IsTrue)

	tbStmt := statement("create table t (a int primary key not null, b varchar(255), key idx_b (b), c int, d int unique)").(*stmts.CreateTableStmt)

	err = dd.CreateTable(ctx, table.Ident{Schema: noExist, Name: tbIdent.Name}, tbStmt.Cols, tbStmt.Constraints)
	c.Assert(errors2.ErrorEqual(err, qerror.ErrDatabaseNotExist), IsTrue)
	err = dd.CreateTable(ctx, tbIdent, tbStmt.Cols, tbStmt.Constraints)
	c.Assert(err, IsNil)
	err = dd.CreateTable(ctx, tbIdent, tbStmt.Cols, tbStmt.Constraints)
	c.Assert(errors2.ErrorEqual(err, ddl.ErrExists), IsTrue)

	tbIdent2 := tbIdent
	tbIdent2.Name = model.NewCIStr("t2")
	tbStmt = statement("create table t2 (a int unique not null)").(*stmts.CreateTableStmt)
	err = dd.CreateTable(ctx, tbIdent2, tbStmt.Cols, tbStmt.Constraints)
	c.Assert(err, IsNil)

	tb, err := handle.Get().TableByName(tbIdent.Schema, tbIdent.Name)
	c.Assert(err, IsNil)
	_, err = tb.AddRecord(ctx, []interface{}{1, "b", 2, 4})
	c.Assert(err, IsNil)

	alterStmt := statement("alter table t add column aa int first").(*stmts.AlterTableStmt)
	dd.AlterTable(ctx, tbIdent, alterStmt.Specs)
	c.Assert(alterStmt.Specs[0].String(), Not(Equals), "")
	// Check indices info
	is := handle.Get()
	tbl, err := is.TableByName(schemaName, tblName)
	c.Assert(err, IsNil)
	c.Assert(tbl, NotNil)
	expectedOffset := make(map[string]int)
	expectedOffset["a"] = 1
	expectedOffset["b"] = 2
	expectedOffset["d"] = 4
	for _, idx := range tbl.Indices() {
		for _, col := range idx.Columns {
			o, ok := expectedOffset[col.Name.L]
			c.Assert(ok, IsTrue)
			c.Assert(col.Offset, Equals, o)
		}
	}
	alterStmt = statement("alter table t add column bb int after b").(*stmts.AlterTableStmt)
	err = dd.AlterTable(ctx, tbIdent, alterStmt.Specs)
	c.Assert(err, IsNil)
	c.Assert(alterStmt.Specs[0].String(), Not(Equals), "")
	// Inserting a duplicated column will cause error.
	alterStmt = statement("alter table t add column bb int after b").(*stmts.AlterTableStmt)
	err = dd.AlterTable(ctx, tbIdent, alterStmt.Specs)
	c.Assert(err, NotNil)

	idxStmt := statement("CREATE INDEX idx_c ON t (c)").(*stmts.CreateIndexStmt)
	idxName := model.NewCIStr(idxStmt.IndexName)
	err = dd.CreateIndex(ctx, tbIdent, idxStmt.Unique, idxName, idxStmt.IndexColNames)
	c.Assert(err, IsNil)
	tbs := handle.Get().SchemaTables(tbIdent.Schema)
	c.Assert(len(tbs), Equals, 2)
	err = dd.DropIndex(ctx, tbIdent.Schema, tbIdent.Name, idxName)
	c.Assert(err, IsNil)
	err = dd.DropTable(ctx, tbIdent)
	c.Assert(err, IsNil)
	tbs = handle.Get().SchemaTables(tbIdent.Schema)
	c.Assert(len(tbs), Equals, 1)

	err = dd.DropSchema(ctx, noExist)
	c.Assert(errors2.ErrorEqual(err, ddl.ErrNotExists), IsTrue)
	err = dd.DropSchema(ctx, tbIdent.Schema)
	c.Assert(err, IsNil)
}
Example #28
0
func (ts *testSuite) TestDDL(c *C) {
	se, _ := tidb.CreateSession(ts.store)
	ctx := se.(context.Context)
	schemaName := model.NewCIStr("test_ddl")
	tblName := model.NewCIStr("t")
	tbIdent := table.Ident{
		Schema: schemaName,
		Name:   tblName,
	}
	noExist := model.NewCIStr("noexist")

	err := sessionctx.GetDomain(ctx).DDL().CreateSchema(ctx, tbIdent.Schema)
	c.Assert(err, IsNil)
	err = sessionctx.GetDomain(ctx).DDL().CreateSchema(ctx, tbIdent.Schema)
	c.Assert(terror.ErrorEqual(err, ddl.ErrExists), IsTrue)

	tbStmt := statement("create table t (a int primary key not null, b varchar(255), key idx_b (b), c int, d int unique)").(*stmts.CreateTableStmt)
	err = sessionctx.GetDomain(ctx).DDL().CreateTable(ctx, table.Ident{Schema: noExist, Name: tbIdent.Name}, tbStmt.Cols, tbStmt.Constraints)
	c.Assert(terror.DatabaseNotExists.Equal(err), IsTrue)

	err = sessionctx.GetDomain(ctx).DDL().CreateTable(ctx, tbIdent, tbStmt.Cols, tbStmt.Constraints)
	c.Assert(err, IsNil)

	err = sessionctx.GetDomain(ctx).DDL().CreateTable(ctx, tbIdent, tbStmt.Cols, tbStmt.Constraints)
	c.Assert(terror.ErrorEqual(err, ddl.ErrExists), IsTrue)

	tb, err := sessionctx.GetDomain(ctx).InfoSchema().TableByName(tbIdent.Schema, tbIdent.Name)
	c.Assert(err, IsNil)
	c.Assert(tb, NotNil)
	_, err = tb.AddRecord(ctx, []interface{}{1, "b", 2, 4}, 0)
	c.Assert(err, IsNil)

	alterStmt := statement("alter table t add column aa int first").(*stmts.AlterTableStmt)
	sessionctx.GetDomain(ctx).DDL().AlterTable(ctx, tbIdent, alterStmt.Specs)
	c.Assert(alterStmt.Specs[0].String(), Not(Equals), "")

	tbl, err := sessionctx.GetDomain(ctx).InfoSchema().TableByName(schemaName, tblName)
	c.Assert(err, IsNil)
	c.Assert(tbl, NotNil)
	expectedOffset := make(map[string]int)
	expectedOffset["a"] = 1
	expectedOffset["b"] = 2
	expectedOffset["d"] = 4
	for _, idx := range tbl.Indices() {
		for _, col := range idx.Columns {
			o, ok := expectedOffset[col.Name.L]
			c.Assert(ok, IsTrue)
			c.Assert(col.Offset, Equals, o)
		}
	}

	alterStmt = statement("alter table t add column bb int after b").(*stmts.AlterTableStmt)
	err = sessionctx.GetDomain(ctx).DDL().AlterTable(ctx, tbIdent, alterStmt.Specs)
	c.Assert(err, IsNil)
	c.Assert(alterStmt.Specs[0].String(), Not(Equals), "")

	// Test add a duplicated column to table, get an error.
	alterStmt = statement("alter table t add column bb int after b").(*stmts.AlterTableStmt)
	err = sessionctx.GetDomain(ctx).DDL().AlterTable(ctx, tbIdent, alterStmt.Specs)
	c.Assert(err, NotNil)

	// Test column schema change in t2.
	tbIdent2 := tbIdent
	tbIdent2.Name = model.NewCIStr("t2")
	tbStmt = statement("create table t2 (a int unique not null)").(*stmts.CreateTableStmt)
	err = sessionctx.GetDomain(ctx).DDL().CreateTable(ctx, tbIdent2, tbStmt.Cols, tbStmt.Constraints)
	c.Assert(err, IsNil)
	tb, err = sessionctx.GetDomain(ctx).InfoSchema().TableByName(tbIdent2.Schema, tbIdent2.Name)
	c.Assert(err, IsNil)
	c.Assert(tb, NotNil)
	rid0, err := tb.AddRecord(ctx, []interface{}{1}, 0)
	c.Assert(err, IsNil)
	rid1, err := tb.AddRecord(ctx, []interface{}{2}, 0)
	c.Assert(err, IsNil)

	alterStmt = statement(`alter table t2 add b enum("bb") first`).(*stmts.AlterTableStmt)
	sessionctx.GetDomain(ctx).DDL().AlterTable(ctx, tbIdent2, alterStmt.Specs)
	c.Assert(alterStmt.Specs[0].String(), Not(Equals), "")
	tb, err = sessionctx.GetDomain(ctx).InfoSchema().TableByName(tbIdent2.Schema, tbIdent2.Name)
	c.Assert(err, IsNil)
	c.Assert(tb, NotNil)
	cols, err := tb.Row(ctx, rid0)
	c.Assert(err, IsNil)
	c.Assert(len(cols), Equals, 2)
	c.Assert(cols[0], Equals, nil)
	c.Assert(cols[1], Equals, int64(1))

	alterStmt = statement(`alter table t2 add c varchar(255) default "abc" after b`).(*stmts.AlterTableStmt)
	sessionctx.GetDomain(ctx).DDL().AlterTable(ctx, tbIdent2, alterStmt.Specs)
	c.Assert(alterStmt.Specs[0].String(), Not(Equals), "")
	tb, err = sessionctx.GetDomain(ctx).InfoSchema().TableByName(tbIdent2.Schema, tbIdent2.Name)
	c.Assert(err, IsNil)
	c.Assert(tb, NotNil)
	cols, err = tb.Row(ctx, rid1)
	c.Assert(err, IsNil)
	c.Assert(len(cols), Equals, 3)
	c.Assert(cols[0], Equals, nil)
	c.Assert(cols[1], Equals, "abc")
	c.Assert(cols[2], Equals, int64(2))
	rid3, err := tb.AddRecord(ctx, []interface{}{mysql.Enum{Name: "bb", Value: 1}, "c", 3}, 0)
	c.Assert(err, IsNil)
	cols, err = tb.Row(ctx, rid3)
	c.Assert(err, IsNil)
	c.Assert(len(cols), Equals, 3)
	c.Assert(cols[0], Equals, mysql.Enum{Name: "bb", Value: 1})
	c.Assert(cols[1], Equals, "c")
	c.Assert(cols[2], Equals, int64(3))

	// Test add column after a not exist column, get an error.
	alterStmt = statement(`alter table t2 add b int after xxxx`).(*stmts.AlterTableStmt)
	err = sessionctx.GetDomain(ctx).DDL().AlterTable(ctx, tbIdent2, alterStmt.Specs)
	c.Assert(err, NotNil)

	// Test add column to a not exist table, get an error.
	tbIdent3 := tbIdent
	tbIdent3.Name = model.NewCIStr("t3")
	alterStmt = statement(`alter table t3 add b int first`).(*stmts.AlterTableStmt)
	err = sessionctx.GetDomain(ctx).DDL().AlterTable(ctx, tbIdent3, alterStmt.Specs)
	c.Assert(err, NotNil)

	// Test drop column.
	alterStmt = statement("alter table t2 drop column b").(*stmts.AlterTableStmt)
	err = sessionctx.GetDomain(ctx).DDL().AlterTable(ctx, tbIdent2, alterStmt.Specs)
	c.Assert(err, IsNil)
	tb, err = sessionctx.GetDomain(ctx).InfoSchema().TableByName(tbIdent2.Schema, tbIdent2.Name)
	c.Assert(err, IsNil)
	c.Assert(tb, NotNil)

	cols, err = tb.Row(ctx, rid0)
	c.Assert(err, IsNil)
	c.Assert(len(cols), Equals, 2)
	c.Assert(cols[0], Equals, "abc")
	c.Assert(cols[1], Equals, int64(1))

	// Test drop a not exist column from table, get an error.
	alterStmt = statement(`alter table t2 drop column xxx`).(*stmts.AlterTableStmt)
	err = sessionctx.GetDomain(ctx).DDL().AlterTable(ctx, tbIdent2, alterStmt.Specs)
	c.Assert(err, NotNil)

	// Test drop column from a not exist table, get an error.
	alterStmt = statement(`alter table t3 drop column a`).(*stmts.AlterTableStmt)
	err = sessionctx.GetDomain(ctx).DDL().AlterTable(ctx, tbIdent3, alterStmt.Specs)
	c.Assert(err, NotNil)

	// Test index schema change.
	idxStmt := statement("CREATE INDEX idx_c ON t (c)").(*stmts.CreateIndexStmt)
	idxName := model.NewCIStr(idxStmt.IndexName)
	err = sessionctx.GetDomain(ctx).DDL().CreateIndex(ctx, tbIdent, idxStmt.Unique, idxName, idxStmt.IndexColNames)
	c.Assert(err, IsNil)
	tbs := sessionctx.GetDomain(ctx).InfoSchema().SchemaTables(tbIdent.Schema)
	c.Assert(len(tbs), Equals, 2)
	err = sessionctx.GetDomain(ctx).DDL().DropIndex(ctx, tbIdent, idxName)
	c.Assert(err, IsNil)

	alterStmt = statement("alter table t add index idx_c (c)").(*stmts.AlterTableStmt)
	err = sessionctx.GetDomain(ctx).DDL().AlterTable(ctx, tbIdent, alterStmt.Specs)
	c.Assert(err, IsNil)

	alterStmt = statement("alter table t drop index idx_c").(*stmts.AlterTableStmt)
	err = sessionctx.GetDomain(ctx).DDL().AlterTable(ctx, tbIdent, alterStmt.Specs)
	c.Assert(err, IsNil)

	alterStmt = statement("alter table t add unique index idx_c (c)").(*stmts.AlterTableStmt)
	err = sessionctx.GetDomain(ctx).DDL().AlterTable(ctx, tbIdent, alterStmt.Specs)
	c.Assert(err, IsNil)

	alterStmt = statement("alter table t drop index idx_c").(*stmts.AlterTableStmt)
	err = sessionctx.GetDomain(ctx).DDL().AlterTable(ctx, tbIdent, alterStmt.Specs)
	c.Assert(err, IsNil)

	err = sessionctx.GetDomain(ctx).DDL().DropTable(ctx, tbIdent)
	c.Assert(err, IsNil)

	tbs = sessionctx.GetDomain(ctx).InfoSchema().SchemaTables(tbIdent.Schema)
	c.Assert(len(tbs), Equals, 1)

	err = sessionctx.GetDomain(ctx).DDL().DropSchema(ctx, noExist)
	c.Assert(terror.ErrorEqual(err, ddl.ErrNotExists), IsTrue)

	err = sessionctx.GetDomain(ctx).DDL().DropSchema(ctx, tbIdent.Schema)
	c.Assert(err, IsNil)
}
Example #29
0
func (ts *testSuite) TestAlterTableColumn(c *C) {
	se, _ := tidb.CreateSession(ts.store)
	ctx := se.(context.Context)
	schemaName := model.NewCIStr("test_alter_add_column")
	tbIdent := table.Ident{
		Schema: schemaName,
		Name:   model.NewCIStr("t"),
	}

	err := sessionctx.GetDomain(ctx).DDL().CreateSchema(ctx, tbIdent.Schema)
	c.Assert(err, IsNil)

	tbStmt := statement("create table t (a int, b int)").(*stmts.CreateTableStmt)
	err = sessionctx.GetDomain(ctx).DDL().CreateTable(ctx, tbIdent, tbStmt.Cols, tbStmt.Constraints)
	c.Assert(err, IsNil)

	alterStmt := statement("alter table t add column c int PRIMARY KEY").(*stmts.AlterTableStmt)
	err = sessionctx.GetDomain(ctx).DDL().AlterTable(ctx, tbIdent, alterStmt.Specs)
	c.Assert(err, NotNil)

	alterStmt = statement("alter table t add column c int AUTO_INCREMENT PRIMARY KEY").(*stmts.AlterTableStmt)
	err = sessionctx.GetDomain(ctx).DDL().AlterTable(ctx, tbIdent, alterStmt.Specs)
	c.Assert(err, NotNil)

	alterStmt = statement("alter table t add column c int UNIQUE").(*stmts.AlterTableStmt)
	err = sessionctx.GetDomain(ctx).DDL().AlterTable(ctx, tbIdent, alterStmt.Specs)
	c.Assert(err, NotNil)

	alterStmt = statement("alter table t add column c int UNIQUE KEY").(*stmts.AlterTableStmt)
	err = sessionctx.GetDomain(ctx).DDL().AlterTable(ctx, tbIdent, alterStmt.Specs)
	c.Assert(err, NotNil)

	alterStmt = statement("alter table t add column c int, add column d int").(*stmts.AlterTableStmt)
	err = sessionctx.GetDomain(ctx).DDL().AlterTable(ctx, tbIdent, alterStmt.Specs)
	c.Assert(err, NotNil)

	// Notice: Now we have not supported.
	// alterStmt = statement("alter table t add column c int KEY").(*stmts.AlterTableStmt)
	// err = sessionctx.GetDomain(ctx).DDL().AlterTable(ctx, tbIdent, alterStmt.Specs)
	// c.Assert(err, NotNil)

	tbIdent2 := table.Ident{
		Schema: schemaName,
		Name:   model.NewCIStr("t1"),
	}

	tbStmt = statement("create table t1 (a int, b int, c int, d int, index A (a, b))").(*stmts.CreateTableStmt)
	err = sessionctx.GetDomain(ctx).DDL().CreateTable(ctx, tbIdent2, tbStmt.Cols, tbStmt.Constraints)
	c.Assert(err, IsNil)

	alterStmt = statement("alter table t1 drop column a").(*stmts.AlterTableStmt)
	err = sessionctx.GetDomain(ctx).DDL().AlterTable(ctx, tbIdent2, alterStmt.Specs)
	c.Assert(err, NotNil)

	alterStmt = statement("alter table t1 drop column b").(*stmts.AlterTableStmt)
	err = sessionctx.GetDomain(ctx).DDL().AlterTable(ctx, tbIdent2, alterStmt.Specs)
	c.Assert(err, NotNil)

	alterStmt = statement("alter table t1 drop column c, drop column d").(*stmts.AlterTableStmt)
	err = sessionctx.GetDomain(ctx).DDL().AlterTable(ctx, tbIdent, alterStmt.Specs)
	c.Assert(err, NotNil)

	err = sessionctx.GetDomain(ctx).DDL().DropSchema(ctx, tbIdent.Schema)
	c.Assert(err, IsNil)
}
Example #30
0
File: main.go Project: pingcap/tidb
func main() {
	tidb.RegisterLocalStore("boltdb", boltdb.Driver{})
	tidb.RegisterStore("tikv", tikv.Driver{})

	runtime.GOMAXPROCS(runtime.NumCPU())

	flag.Parse()
	if *version {
		printer.PrintRawTiDBInfo()
		os.Exit(0)
	}

	leaseDuration := parseLease()
	tidb.SetSchemaLease(leaseDuration)

	cfg := &server.Config{
		Addr:         fmt.Sprintf("%s:%s", *host, *port),
		LogLevel:     *logLevel,
		StatusAddr:   fmt.Sprintf(":%s", *statusPort),
		Socket:       *socket,
		ReportStatus: *reportStatus,
	}

	// set log options
	if len(*logFile) > 0 {
		err := log.SetOutputByName(*logFile)
		if err != nil {
			log.Fatal(errors.ErrorStack(err))
		}
		log.SetRotateByDay()
		log.SetHighlighting(false)
	}

	if joinCon != nil && *joinCon > 0 {
		plan.JoinConcurrency = *joinCon
	}
	plan.AllowCartesianProduct = *crossJoin
	// Call this before setting log level to make sure that TiDB info could be printed.
	printer.PrintTiDBInfo()
	log.SetLevelByString(cfg.LogLevel)

	store := createStore()

	if *enablePS {
		perfschema.EnablePerfSchema()
	}
	if *binlogSocket != "" {
		createBinlogClient()
	}

	// Create a session to load information schema.
	se, err := tidb.CreateSession(store)
	if err != nil {
		log.Fatal(errors.ErrorStack(err))
	}
	se.Close()

	var driver server.IDriver
	driver = server.NewTiDBDriver(store)
	var svr *server.Server
	svr, err = server.NewServer(cfg, driver)
	if err != nil {
		log.Fatal(errors.ErrorStack(err))
	}

	sc := make(chan os.Signal, 1)
	signal.Notify(sc,
		syscall.SIGHUP,
		syscall.SIGINT,
		syscall.SIGTERM,
		syscall.SIGQUIT)

	go func() {
		sig := <-sc
		log.Infof("Got signal [%d] to exit.", sig)
		svr.Close()
		os.Exit(0)
	}()

	go systimemon.StartMonitor(time.Now, func() {
		log.Error("error: system time jump backward")
	})

	pushMetric(*metricsAddr, time.Duration(*metricsInterval)*time.Second)

	log.Error(svr.Run())
}