Skip to content

Commit 72d6881

Browse files
authored
GO support for escaped characters (#3381)
1 parent e3be426 commit 72d6881

2 files changed

Lines changed: 33 additions & 3 deletions

File tree

gremlin-go/driver/gremlinlang.go

Lines changed: 27 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -110,16 +110,40 @@ func (gl *GremlinLang) addToGremlin(name string, args ...interface{}) error {
110110
return nil
111111
}
112112

113+
// escapeString escapes a string value for safe embedding in a GremlinLang script.
114+
func escapeString(s string) string {
115+
var sb strings.Builder
116+
for _, c := range s {
117+
switch c {
118+
case '\\':
119+
sb.WriteString(`\\`)
120+
case '"':
121+
sb.WriteString(`\"`)
122+
case '\n':
123+
sb.WriteString(`\n`)
124+
case '\r':
125+
sb.WriteString(`\r`)
126+
case '\t':
127+
sb.WriteString(`\t`)
128+
case '\b':
129+
sb.WriteString(`\b`)
130+
case '\f':
131+
sb.WriteString(`\f`)
132+
default:
133+
sb.WriteRune(c)
134+
}
135+
}
136+
return sb.String()
137+
}
138+
113139
func (gl *GremlinLang) argAsString(arg interface{}) (string, error) {
114140
if arg == nil {
115141
return "null", nil
116142
}
117-
// we are concerned with both single and double quotes and %q in fmt only escapes double quotes
118-
escapeQuotes := strings.NewReplacer(`'`, `\'`, `"`, `\"`)
119143

120144
switch v := arg.(type) {
121145
case string:
122-
return fmt.Sprintf("\"%s\"", escapeQuotes.Replace(v)), nil
146+
return fmt.Sprintf("\"%s\"", escapeString(v)), nil
123147
case bool:
124148
return strconv.FormatBool(v), nil
125149
case int8, uint8:

gremlin-go/driver/gremlinlang_test.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -674,6 +674,12 @@ func Test_GremlinLang(t *testing.T) {
674674
},
675675
equals: "g.inject(NaN).is(eq(NaN))",
676676
},
677+
{
678+
assert: func(g *GraphTraversalSource) *GraphTraversal {
679+
return g.V().Has("name", "\"marko\n\r\t\b\f\"")
680+
},
681+
equals: "g.V().has(\"name\",\"\\\"marko\\n\\r\\t\\b\\f\\\"\")",
682+
},
677683
}
678684

679685
var testsToRun []test

0 commit comments

Comments
 (0)