Skip to content

Commit

Permalink
ddl: add check when add foreign key. (pingcap#8050) (pingcap#8421)
Browse files Browse the repository at this point in the history
  • Loading branch information
crazycs520 authored and zz-jason committed Nov 24, 2018
1 parent a804be8 commit 420d8da
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 3 deletions.
7 changes: 5 additions & 2 deletions ddl/ddl_api.go
Expand Up @@ -1713,13 +1713,16 @@ func (d *ddl) CreateIndex(ctx sessionctx.Context, ti ast.Ident, unique bool, ind
return errors.Trace(err)
}

func buildFKInfo(fkName model.CIStr, keys []*ast.IndexColName, refer *ast.ReferenceDef) (*model.FKInfo, error) {
func buildFKInfo(fkName model.CIStr, keys []*ast.IndexColName, refer *ast.ReferenceDef, cols []*table.Column) (*model.FKInfo, error) {
var fkInfo model.FKInfo
fkInfo.Name = fkName
fkInfo.RefTable = refer.Table.Name

fkInfo.Cols = make([]model.CIStr, len(keys))
for i, key := range keys {
if table.FindCol(cols, key.Column.Name.O) == nil {
return nil, errKeyColumnDoesNotExits.Gen("key column %s doesn't exist in table", key.Column.Name)
}
fkInfo.Cols[i] = key.Column.Name
}

Expand Down Expand Up @@ -1747,7 +1750,7 @@ func (d *ddl) CreateForeignKey(ctx sessionctx.Context, ti ast.Ident, fkName mode
return errors.Trace(infoschema.ErrTableNotExists.GenByArgs(ti.Schema, ti.Name))
}

fkInfo, err := buildFKInfo(fkName, keys, refer)
fkInfo, err := buildFKInfo(fkName, keys, refer, t.Cols())
if err != nil {
return errors.Trace(err)
}
Expand Down
7 changes: 6 additions & 1 deletion ddl/ddl_db_test.go
Expand Up @@ -1447,9 +1447,14 @@ func (s *testDBSuite) TestTableForeignKey(c *C) {
s.tk = testkit.NewTestKit(c, s.store)
s.tk.MustExec("use test")
s.tk.MustExec("create table t1 (a int, b int);")
// test create table with foreign key.
failSQL := "create table t2 (c int, foreign key (a) references t1(a));"
s.testErrorCode(c, failSQL, tmysql.ErrKeyColumnDoesNotExits)
s.tk.MustExec("drop table if exists t1,t2;")
// test add foreign key.
s.tk.MustExec("create table t3 (a int, b int);")
failSQL = "alter table t1 add foreign key (c) REFERENCES t3(a);"
s.testErrorCode(c, failSQL, tmysql.ErrKeyColumnDoesNotExits)
s.tk.MustExec("drop table if exists t1,t2,t3;")
}

func (s *testDBSuite) TestCreateTableWithPartition(c *C) {
Expand Down

0 comments on commit 420d8da

Please sign in to comment.