diff --git a/ddl/column.go b/ddl/column.go index e4295c8d6b9eb..10f6011ba0432 100644 --- a/ddl/column.go +++ b/ddl/column.go @@ -602,10 +602,21 @@ func generateOriginDefaultValue(col *model.ColumnInfo) (interface{}, error) { var err error odValue := col.GetDefaultValue() if odValue == nil && mysql.HasNotNullFlag(col.Flag) { - zeroVal := table.GetZeroValue(col) - odValue, err = zeroVal.ToString() - if err != nil { - return nil, errors.Trace(err) + switch col.Tp { + // Just use enum field's first element for OriginDefaultValue. + case mysql.TypeEnum: + defEnum, verr := types.ParseEnumValue(col.FieldType.Elems, 1) + if verr != nil { + return nil, errors.Trace(verr) + } + defVal := types.NewMysqlEnumDatum(defEnum) + return defVal.ToString() + default: + zeroVal := table.GetZeroValue(col) + odValue, err = zeroVal.ToString() + if err != nil { + return nil, errors.Trace(err) + } } } diff --git a/ddl/db_integration_test.go b/ddl/db_integration_test.go index 5f251057ababa..9806251836994 100644 --- a/ddl/db_integration_test.go +++ b/ddl/db_integration_test.go @@ -2059,3 +2059,32 @@ func (s *testIntegrationSuite3) TestIssue20490(c *C) { tk.MustQuery("select b from issue20490 order by a;").Check(testkit.Rows("1", "1", "")) } + +func (s *testIntegrationSuite3) TestIssue20741WithEnumField(c *C) { + tk := testkit.NewTestKit(c, s.store) + tk.MustExec("use test") + tk.MustExec("drop table if exists issue20741") + tk.MustExec("create table issue20741(id int primary key, c int)") + tk.MustExec("insert into issue20741(id, c) values(1, 2), (2, 2)") + tk.MustExec("alter table issue20741 add column cc enum('a', 'b', 'c', 'd') not null") + tk.MustExec("update issue20741 set c=2 where id=1") + tk.MustQuery("select * from issue20741").Check(testkit.Rows("1 2 a", "2 2 a")) + tk.MustQuery("select * from issue20741 where cc = 0").Check(testkit.Rows()) + tk.MustQuery("select * from issue20741 where cc = 1").Check(testkit.Rows("1 2 a", "2 2 a")) +} + +func (s *testIntegrationSuite3) TestIssue20741WithSetField(c *C) { + tk := testkit.NewTestKit(c, s.store) + tk.MustExec("use test") + tk.MustExec("drop table if exists issue20741_2") + tk.MustExec("create table issue20741_2(id int primary key, c int)") + tk.MustExec("insert into issue20741_2(id, c) values(1, 2), (2, 2)") + tk.MustExec("alter table issue20741_2 add column cc set('a', 'b', 'c', 'd') not null") + tk.MustExec("update issue20741_2 set c=2 where id=1") + tk.MustQuery("select * from issue20741_2").Check(testkit.Rows("1 2 ", "2 2 ")) + tk.MustQuery("select * from issue20741_2 where cc = 0").Check(testkit.Rows("1 2 ", "2 2 ")) + tk.MustQuery("select * from issue20741_2 where cc = 1").Check(testkit.Rows()) + _, err := tk.Exec("insert into issue20741_2(id, c) values (3, 3)") + c.Assert(err, NotNil) + c.Assert(err.Error(), Equals, "[table:1364]Field 'cc' doesn't have a default value") +}