Repository: pingcap/tidb (Go)

Issue:
The default value of a newly added enum column is set improperly
## Bug Report

Please answer these questions before submitting your issue. Thanks!

### 1. Minimal reproduce step (Required)

<!-- a step by step guide for reproducing the bug. -->
```sql
drop table if exists t;
create table t (id int primary key, c int);
insert into t (id, c) values (1, 1), (2, 2);

alter table t add column cc enum('a','b','c','d','e') not null;
update t set c = 2 where id = 1;
select * from t;
select * from t where cc = 0;
select * from t where cc = 1;
```

### 2. What did you expect to see? (Required)

```
mysql> update t set c = 2 where id = 1;
Query OK, 1 row affected (0.06 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> select * from t;
+----+------+----+
| id | c    | cc |
+----+------+----+
|  1 |    2 | a  |
|  2 |    2 | a  |
+----+------+----+
2 rows in set (0.05 sec)

mysql> select * from t where cc = 0;
Empty set (0.05 sec)

mysql> select * from t where cc = 1;
+----+------+----+
| id | c    | cc |
+----+------+----+
|  1 |    2 | a  |
|  2 |    2 | a  |
+----+------+----+
2 rows in set (0.06 sec)

```

### 3. What did you see instead (Required)

```
mysql> update t set c = 2 where id = 1;
ERROR 1265 (01000): Data truncated for column '%s' at row %d

mysql> select * from t;
+----+------+----+
| id | c    | cc |
+----+------+----+
|  1 |    1 |    |
|  2 |    2 |    |
+----+------+----+
2 rows in set, 1 warning (0.06 sec)

mysql> select * from t where cc = 0;
+----+------+----+
| id | c    | cc |
+----+------+----+
|  1 |    1 |    |
|  2 |    2 |    |
+----+------+----+
2 rows in set, 1 warning (0.06 sec)

mysql> select * from t where cc = 1;
Empty set, 1 warning (0.06 sec)

```

### 4. What is your TiDB version? (Required)

<!-- Paste the output of SELECT tidb_version() -->
master
release-4.0
## Score

- 600

## Mentor

- @wjhuang2016 


Discussion:
/pick-up

It is not a pickable issue!

<details>
<summary>Details</summary>

**Tip**    : If you want this issue to be picked, you need to add a `challenge-program` label to it.

**Warning**: None
</details>
    
cc @bb7133 

It has been added to the challenge program, but your issue description has some problems.

<details>
<summary>Details</summary>

**Tip**    : 
    You need to ensure that the description of the issue follows the following template:
    
    ```
    ## Score

    - ${score}

    ## Mentor

    - ${mentor}
    ```
    

**Warning**: The description format for this issue is wrong.
</details>
    

It has been added to the challenge program, but your issue description has some problems.

<details>
<summary>Details</summary>

**Tip**    : 
    You need to ensure that the description of the issue follows the following template:
    
    ```
    ## Score

    - ${score}

    ## Mentor

    - ${mentor}
    ```
    

**Warning**: The description format for this issue is wrong.
</details>
    

The description of issue updated, but still has some problems.

<details>
<summary>Details</summary>

**Tip**    : 
    You need to ensure that the description of the issue follows the following template:
    
    ```
    ## Score

    - ${score}

    ## Mentor

    - ${mentor}
    ```
    

**Warning**: The description format for this issue is wrong.
</details>
    

The description of issue updated, but still has some problems.

<details>
<summary>Details</summary>

**Tip**    : 
    You need to ensure that the description of the issue follows the following template:
    
    ```
    ## Score

    - ${score}

    ## Mentor

    - ${mentor}
    ```
    

**Warning**: The description format for this issue is wrong.
</details>
    

The description of issue updated, but still has some problems.

<details>
<summary>Details</summary>

**Tip**    : 
    You need to ensure that the description of the issue follows the following template:
    
    ```
    ## Score

    - ${score}

    ## Mentor

    - ${mentor}
    ```
    

**Warning**: The description format for this issue is wrong.
</details>
    
/pick-up
Pick up success.
## Please edit this comment to complete the following information

### Not a bug

1. Remove the 'type/bug' label
2. Add notes to indicate why it is not a bug

### Duplicate bug

1. Add the 'type/duplicate' label
2. Add the link to the original bug

### Bug

Note: Make Sure that 'component', and 'severity' labels are added
Example for how to fill out the template: https://github.com/pingcap/tidb/issues/20100

#### 1. Root Cause Analysis (RCA) (optional) 
<!-- Write down the reason why this bug occurs -->

#### 2. Symptom (optional)

<!-- What will the user see when this bug occurs. The error message may be in the terminal, log or monitoring -->

#### 3. All Trigger Conditions (optional)

<!-- All the user scenarios that may trigger this bug -->

#### 4. Workaround (optional)

#### 5. Affected versions

<!--
In the format of [start_version:end_version], multiple version ranges are
accepted. If the bug only affects the unreleased version, please input:
"unreleased". For example:

Notes:
  1. Do not use any white spaces in '[]'.
  2. The range in '[]' is a closed interval
  3. The version format is `v$Major.$Minor.$Patch`, the $Majoy and $Minor
     number in a version range should be the same. [v3.0.1:v3.1.2] is
     invalid because the $Minor number of the version range is different.

Example 1: [v3.0.1:v3.0.5], [v4.0.1:v4.0.5]
Example 2: unreleased
-->

#### 6. Fixed versions

<!--
The first released version that contains this fix in each minor version. If the bug's affected version has been released, the fixed version should be a detailed version number; If the bug doesn't affect any released version, the fixed version can be "master";  

Example 1: v3.0.13, v4.0.5
Example 2: master
-->



Patch:
diff --git a/ddl/column.go b/ddl/column.go
index 2874bd3d587c1..f6b4e87d7b22e 100644
--- a/ddl/column.go
+++ b/ddl/column.go
@@ -1659,10 +1659,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.NewCollateMysqlEnumDatum(defEnum, col.Collate)
+			return defVal.ToString()
+		default:
+			zeroVal := table.GetZeroValue(col)
+			odValue, err = zeroVal.ToString()
+			if err != nil {
+				return nil, errors.Trace(err)
+			}
 		}
 	}
 


Test patch:
diff --git a/ddl/db_integration_test.go b/ddl/db_integration_test.go
index aedf79146b1c2..fe20bc54c028f 100644
--- a/ddl/db_integration_test.go
+++ b/ddl/db_integration_test.go
@@ -2531,6 +2531,35 @@ func (s *testIntegrationSuite3) TestIssue20490(c *C) {
 	tk.MustQuery("select b from issue20490 order by a;").Check(testkit.Rows("1", "1", "<nil>"))
 }
 
+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")
+}
+
 // TestDefaultValueIsLatin1 for issue #18977
 func (s *testIntegrationSuite3) TestEnumAndSetDefaultValue(c *C) {
 	tk := testkit.NewTestKit(c, s.store)