fix: escape quote and backslash for ClickHouse value (#3377)

This commit is contained in:
Srikanth Chekuri 2023-08-18 15:52:59 +05:30 committed by GitHub
parent 9488ce8585
commit 6fb071cf37
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 22 additions and 2 deletions

View File

@ -141,6 +141,13 @@ func ValidateAndCastValue(v interface{}, dataType v3.AttributeKeyDataType) (inte
}
}
func quoteEscapedString(str string) string {
// https://clickhouse.com/docs/en/sql-reference/syntax#string
str = strings.ReplaceAll(str, `\`, `\\`)
str = strings.ReplaceAll(str, `'`, `\'`)
return str
}
// ClickHouseFormattedValue formats the value to be used in clickhouse query
func ClickHouseFormattedValue(v interface{}) string {
// if it's pointer convert it to a value
@ -152,7 +159,7 @@ func ClickHouseFormattedValue(v interface{}) string {
case float32, float64:
return fmt.Sprintf("%f", x)
case string:
return fmt.Sprintf("'%s'", x)
return fmt.Sprintf("'%s'", quoteEscapedString(x))
case bool:
return fmt.Sprintf("%v", x)
@ -164,7 +171,7 @@ func ClickHouseFormattedValue(v interface{}) string {
case string:
str := "["
for idx, sVal := range x {
str += fmt.Sprintf("'%s'", sVal)
str += fmt.Sprintf("'%s'", quoteEscapedString(sVal.(string)))
if idx != len(x)-1 {
str += ","
}

View File

@ -362,6 +362,19 @@ var testClickHouseFormattedValueData = []struct {
value: []interface{}{&one, &one},
want: "[1,1]",
},
{
name: "string with single quote",
value: "test'1",
want: "'test\\'1'",
},
{
name: "[]interface{} with string with single quote",
value: []interface{}{
"test'1",
"test'2",
},
want: "['test\\'1','test\\'2']",
},
}
func TestClickHouseFormattedValue(t *testing.T) {