Răsfoiți Sursa

fix: the new RawFieldNames considers the tag with options. (#1663)

Co-authored-by: JinfaWang <wangjinfa@iie.ac.cn>
Mervin.Wong 3 ani în urmă
părinte
comite
93d524b797
2 a modificat fișierele cu 35 adăugiri și 3 ștergeri
  1. 18 3
      core/stores/builder/builder.go
  2. 17 0
      core/stores/builder/builder_test.go

+ 18 - 3
core/stores/builder/builder.go

@@ -41,10 +41,25 @@ func RawFieldNames(in interface{}, postgresSql ...bool) []string {
 				out = append(out, fmt.Sprintf("`%s`", fi.Name))
 			}
 		default:
-			if pg {
-				out = append(out, tagv)
+			//get tag name with the tag opton, e.g.:
+			//`db:"id"`
+			//`db:"id,type=char,length=16"`
+			//`db:",type=char,length=16"`
+			if strings.Contains(tagv, ",") {
+				tagv = strings.TrimSpace(strings.Split(tagv, ",")[0])
+			}
+			if tagv != "" {
+				if pg {
+					out = append(out, tagv)
+				} else {
+					out = append(out, fmt.Sprintf("`%s`", tagv))
+				}
 			} else {
-				out = append(out, fmt.Sprintf("`%s`", tagv))
+				if pg {
+					out = append(out, fi.Name)
+				} else {
+					out = append(out, fmt.Sprintf("`%s`", fi.Name))
+				}
 			}
 		}
 	}

+ 17 - 0
core/stores/builder/builder_test.go

@@ -22,3 +22,20 @@ func TestFieldNames(t *testing.T) {
 		assert.Equal(t, expected, out)
 	})
 }
+
+type mockedUserWithOptions struct {
+	ID       string `db:"id" json:"id,omitempty"`
+	UserName string `db:"user_name,type=varchar,length=255" json:"userName,omitempty"`
+	Sex      int    `db:"sex" json:"sex,omitempty"`
+	UUID     string `db:",type=varchar,length=16" uuid:"uuid,omitempty"`
+	Age      int    `db:"age" json:"age"`
+}
+
+func TestFieldNamesWithTagOptions(t *testing.T) {
+	t.Run("new", func(t *testing.T) {
+		var u mockedUserWithOptions
+		out := RawFieldNames(&u)
+		expected := []string{"`id`", "`user_name`", "`sex`", "`UUID`", "`age`"}
+		assert.Equal(t, expected, out)
+	})
+}