Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ddl: add check when add foreign key. (#8050) #8421

Merged
merged 4 commits into from
Nov 24, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions ddl/ddl_api.go
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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