Skip to content

Commit 5eaf05a

Browse files
authored
fix: Allow escaped double quotes in struct tag parser (#7631)
* fix: support escaping double quotes in struct tag parser * chore: resolve lint errors in util_test.go
1 parent 2c3d109 commit 5eaf05a

File tree

2 files changed

+20
-14
lines changed

2 files changed

+20
-14
lines changed

schema/utils.go

Lines changed: 12 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -17,25 +17,23 @@ func ParseTagSetting(str string, sep string) map[string]string {
1717
settings := map[string]string{}
1818
names := strings.Split(str, sep)
1919

20+
var parsedNames []string
2021
for i := 0; i < len(names); i++ {
21-
j := i
22-
if len(names[j]) > 0 {
23-
for {
24-
if names[j][len(names[j])-1] == '\\' {
25-
i++
26-
names[j] = names[j][0:len(names[j])-1] + sep + names[i]
27-
names[i] = ""
28-
} else {
29-
break
30-
}
31-
}
22+
s := names[i]
23+
for strings.HasSuffix(s, "\\") && i+1 < len(names) {
24+
i++
25+
s = s[:len(s)-1] + sep + names[i]
3226
}
27+
parsedNames = append(parsedNames, s)
28+
}
3329

34-
values := strings.Split(names[j], ":")
30+
for _, tag := range parsedNames {
31+
values := strings.Split(tag, ":")
3532
k := strings.TrimSpace(strings.ToUpper(values[0]))
36-
3733
if len(values) >= 2 {
38-
settings[k] = strings.Join(values[1:], ":")
34+
val := strings.Join(values[1:], ":")
35+
val = strings.ReplaceAll(val, `\"`, `"`)
36+
settings[k] = val
3937
} else if k != "" {
4038
settings[k] = k
4139
}

schema/utils_test.go

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,3 +22,11 @@ func TestRemoveSettingFromTag(t *testing.T) {
2222
}
2323
}
2424
}
25+
26+
func TestParseTagSettingWithDoubleQuoteEscape(t *testing.T) {
27+
tag := `gorm:"expression:to_tsvector('english', \"Name\")"`
28+
settings := ParseTagSetting(reflect.StructTag(tag).Get("gorm"), ";")
29+
if v, ok := settings["EXPRESSION"]; !ok || v != `to_tsvector('english', "Name")` {
30+
t.Errorf("ParseTagSetting did not handle escaped double quotes correctly: got %#v", v)
31+
}
32+
}

0 commit comments

Comments
 (0)