sql: fix error when use true in check constraint expression (#44833)

close pingcap/tidb#44689
This commit is contained in:
fzzf678
2023-06-20 21:51:07 +08:00
committed by GitHub
parent 7112702e15
commit 894c325073
2 changed files with 27 additions and 5 deletions

View File

@ -1123,3 +1123,18 @@ func TestAlterEnforcedConstraintStateChange(t *testing.T) {
tk.MustExec("alter table t alter constraint c1 enforced")
tk.MustQuery("select * from t").Check(testkit.Rows("12"))
}
func TestIssue44689(t *testing.T) {
store := testkit.CreateMockStore(t)
tk := testkit.NewTestKit(t, store)
tk.MustExec("USE test")
for _, expr := range []string{"true", "false"} {
tk.MustExec("DROP TABLE IF EXISTS t0, t1, t2")
tk.MustExec(fmt.Sprintf("CREATE TABLE t0(c1 NUMERIC CHECK(%s))", expr))
tk.MustExec(fmt.Sprintf("CREATE TABLE t1(c1 NUMERIC, CHECK(%s))", expr))
tk.MustExec("CREATE TABLE t2(c1 NUMERIC)")
tk.MustExec(fmt.Sprintf("ALTER TABLE t2 ADD CONSTRAINT CHECK(%s)", expr))
}
}

View File

@ -1997,13 +1997,20 @@ func BuildTableInfo(
}
} else {
// Check the column-type constraint dependency.
if len(dependedColsMap) != 1 {
if len(dependedColsMap) > 1 {
return nil, dbterror.ErrColumnCheckConstraintReferOther.GenWithStackByArgs(constr.Name)
} else if len(dependedColsMap) == 0 {
// If dependedCols is empty, the expression must be true/false.
valExpr, ok := constr.Expr.(*driver.ValueExpr)
if !ok || !mysql.HasIsBooleanFlag(valExpr.GetType().GetFlag()) {
return nil, errors.Trace(errors.New("unsupported expression in check constraint"))
}
} else {
if _, ok := dependedColsMap[constr.InColumnName]; !ok {
return nil, dbterror.ErrColumnCheckConstraintReferOther.GenWithStackByArgs(constr.Name)
}
dependedCols = []model.CIStr{model.NewCIStr(constr.InColumnName)}
}
if _, ok := dependedColsMap[constr.InColumnName]; !ok {
return nil, dbterror.ErrColumnCheckConstraintReferOther.GenWithStackByArgs(constr.Name)
}
dependedCols = []model.CIStr{model.NewCIStr(constr.InColumnName)}
}
// check auto-increment column
if table.ContainsAutoIncrementCol(dependedCols, tbInfo) {